开发者

What is an algorithm for joining PCM files?

What is 开发者_如何转开发an algorithm for joining PCM files? I have several PCM files I need to Join them in a way like speakers are speac at the same time.

So How to Join PCM files?


First find a way to process them sample by sample, then just add the samples from all streams together.

You will run into the problem of overflows. If that happens just clamp the resulting value to the maximum/minimum sample value.

You may also want to offer an option to scale the output before clamping to the user and you may also want to report some statistics how often (per second or so) clamping happed, so the user has some control over the sound quality.


PCM audio files have a header and consecutive samples of audio data. You need to read the header and could use it in the composite (mixed) file header.

FILE    *fpIn;  // Input file pointer 

char    temp[2*FrameSize];

        char inFile[]="input_1.wav" ;
char outFile[]="result.wav" ;


if ((fpIn = fopen(inFile,"rb")) == NULL )
    {
        printf("Can't open input file\n");
        exit(0);
    }

    if ((fpOut = fopen(outFile,"wb")) == NULL )
    {
        printf("Can't open data file\n");
        exit(0);
    }


// Cut the wav headers 44 byte
    fread(temp,sizeof(char),44,fpIn);    // Remove wave header from input file


for the writing back 
   fwrite(temp,sizeof(char),22*2,fpOut);  // Add wave header from input file2


while(fread(temp, sizeof(char),N*2,fpIn) == (unsigned short)(2*N))
    {
        for (i=0;i<N;i++)             // Get PCM input data
        {
            input1[i] = (temp[2*i]&0xFF)|(temp[2*i+1]<<8);
        }

        // Mixing logic goes here 

        for (j=0, i=0;i<N;i++)
        {

            input[i]=0;

            temp[j++] = input [i]&0xFF;
            temp[j++] = (input [i]>>8)&0xFF;
        }
        fwrite(temp,sizeof(char),N*2,fpOut);  // Save result 
    }
    fclose(fpOut);
    fclose(fpIn);

The above code shows how to read and write wav files, you need to implement the mixing logic with weighted factors so on, eg. Output = alpha. Input1 + (1- alpha) Input2 // where alpha is between 0 and 1 depends on how you like add Input 1 vs Input 2. if alpha =0.5 both are added evenly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜