Exemple de code pour Android AudioTrack Mélange

J'ai deux sons PCM fichier dans le dossier de ressources. J'ai utilisé inputstream et converti en objet bytearray.

Puis j'ai traité par normalisé et en ajoutant de la musique 1 et de la musique2 et de sortie pour le tableau d'octets de sortie. Enfin, placez le tableau de sortie et le nourrir à la AudioTrack.

Évidemment, je n'entends rien et quelque chose est faux.

 private void mixSound() throws IOException {
InputStream in1=getResources().openRawResource(R.raw.cheerapp2);      
InputStream in2=getResources().openRawResource(R.raw.buzzer2);
byte[] music1 = null;
music1= new byte[in1.available()]; 
music1=convertStreamToByteArray(in1);
in1.close();
byte[] music2 = null;
music2= new byte[in2.available()]; 
music2=convertStreamToByteArray(in2);
in2.close();
byte[] output = new byte[music1.length];
audioTrack.play();
for(int i=0; i < output.length; i++){
float samplef1 = music1[i] / 128.0f;      //    2^7=128
float samplef2 = music2[i] / 128.0f;
float mixed = samplef1 + samplef2;
//reduce the volume a bit:
mixed *= 0.8;
//hard clipping
if (mixed > 1.0f) mixed = 1.0f;
if (mixed < -1.0f) mixed = -1.0f;
byte outputSample = (byte)(mixed * 128.0f);
output[i] = outputSample;
audioTrack.write(output, 0, i);
}   //for loop
public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[10240];
int i = Integer.MAX_VALUE;
while ((i = is.read(buff, 0, buff.length)) > 0) {
baos.write(buff, 0, i);
}
return baos.toByteArray(); //be sure to close InputStream in calling function
}

OriginalL'auteur jason white | 2013-02-27