views:

149

answers:

3

Hi

I am writing raw audio bytes from two files into a new wav file to combine the two files. The resultant file which is created has the contents of both the audio clips but there is also a lot of noise in the file.

Can someone point me to a good example which shows how to write raw audio bytes to a file? Here's the basic logic that I am following

SInt32 leftSample1 = ReadSampleFromFile1(music_iter1);
leftSample1 = (SInt32)((float) leftSample1 * 0.7071); //to avoid clipping

SInt32 leftStereoSample2 = ReadLeftSample(music_iter2);
leftStereoSample2 += leftSample1;
if (leftStereoSample2 > 32767)
leftStereoSample2 = 32767;
else if (leftStereoSample2 < -32768
leftStereoSample2 = -32768;
// write leftStereoSample2 to the file
//do the same as left sample to right sample also

++music_iter2;
++music_iter1;

Thanks.

A: 

Your tests for 65535 and -65536 are incorrect (would need 17 bits). Try 32767 and -32768.

Dipstick
Did so. Still getting the same results. Any other ideas? Thanks
lostInTransit
Editing the question. I still get the noise
lostInTransit
+1  A: 

how many times are these returning true?

if (leftStereoSample2 > 32767)
leftStereoSample2 = 32767;
else if (leftStereoSample2 < -32768
leftStereoSample2 = -32768;

just because you are not clipping, (because you are forcing it not to) does not mean you wont get artifacts (distortion) etc when you truncate the waves like that. i would see how often that was happening.

core audio has mixers. smart people have written code to deal with this kind of stuff already, so we dont have to :) MultiChannelMixer is one that does stereo mixing. check it out.

Aran Mulholland
A: 

I'm not sure the line of code to "prevent clipping" is actually doing it's job; wouldn't you need to effectively turn down both streams before joining them?

Try combining two much, much quieter files. And instead of 0.7071 on both files, try 0.5. Or just use MultiChannelMixer, as suggested by Aran.

Dean J