问题
I'm trying to develop an Android aplication that uses some sounds and mix them together for creating music compositions. At the beggining I tried just to reproduce sounds at the same time, but when I was doing that, they got disinchronized, and after several hours reading forums I realized that the best way to reproduce several sounds at the same time in loop mode is just to merge the audio files in one and then reproduce them as a single file.
Here is the code I'm using:
//Oppening file 1
InputStream is = getAssets().open("sounds/sound_1.ogg");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
//End Oppening file 1
//Oppening file 2
InputStream is_2 = getAssets().open("sounds/sound_2.ogg");
int size_2 = is_2.available();
byte[] buffer_2 = new byte[size_2];
is_2.read(buffer_2);
is_2.close();
//End Oppening file 2
//Get Bigger size and Merge Files
int total_size =0;
byte[] buffer_final;
if(buffer.length>buffer_2.length){
total_size = buffer_2.length;
}else{
total_size = buffer.length-1;
}
buffer_final= new byte[total_size];
for(int i=30; i<total_size-30;i++){
float a =buffer[i];
float b =buffer_2[i];
float c = (a+b)/2;
buffer_final[i]=(byte) c;
}
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer_final);
fos.close();
And after that, using soundPool I read the resulting file and try to reproduce it.
If i use this formula without merging the files (so, using only one sound, creating a new file, and then reading it, it works perfectly, so I assume that the problem is in the file merging, that maybe is not as easy as just adding the bytes together and then divide by 2.
After doing this, the log tells me this:
Unable to load sample (null).
And ofc, when I try to reproduce the log says that the sample is not ready.
Any help about this please? I've been googleing for it for weeks and I couldn't solve it ...
It's my first time programming Android, and also Audio so I'm a bit lost.
The question would be, how can I mix this sounds? I'm I in the right way for doing it? Where is the problem?
Thanks for reading and helping :)
回答1:
If you were using raw PCM data, averaging the samples would work fine. What you need to do is convert the OGG file into a PCM buffer first. If you'd like to keep the output as OGG, you'll need to convert that back after you're done.
My experience is mostly with MP3 libraries rather than OGG, but I hear good things about JOrbis.
回答2:
In this way
soundPool = new SoundPool(NUM_SOUNDS, AudioManager.STREAM_MUSIC, 0);
NUM_SOUNDS is the number sounds soundPool can play togheter.
来源:https://stackoverflow.com/questions/12687458/android-how-to-mix-2-audio-files-and-reproduce-them-with-soundpool