我有两个属性为44khz,立体声通道和16位的wav文件。我试图在android中使用audiotrack混合它们。我能够混合它们。但我在玩的时候会发出声响。如何消除噪音。
以下是我的代码:
int frequency = 44100;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_STEREO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
int minbufferSize = AudioTrack.getMinBufferSize(frequency, channelConfiguration,audioEncoding);
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, frequency,
channelConfiguration, audioEncoding, minbufferSize,
AudioTrack.MODE_STREAM);
int bufferSize = 512;
int count = 0;
int count2 = 0;
byte[] data = new byte[bufferSize];
byte[] data2 = new byte[bufferSize];
byte[] data3 = new byte[bufferSize];
try{
FileInputStream fileInputStream = new FileInputStream("/sdcard/file1.wav");
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
FileInputStream fileInputStream2 = new FileInputStream("/sdcard/file2.wav");
DataInputStream dataInputStream2 = new DataInputStream(fileInputStream2);
audioTrack.play();
while((count = dataInputStream.read(data, 0, bufferSize)) > -1 && (count2 = dataInputStream2.read(data2, 0, bufferSize)) > -1){
for (int i=0;i<data3.length;i++){
float samplef1 = (data[i] / 128.0f);
float samplef2 = (data2[i] / 128.0f);
float mixed = samplef1 + samplef2;
// reduce the volume a bit:
mixed *= 0.9;
// hard clipping
if (mixed > 1.0f) mixed = 1.0f;
if (mixed < -1.0f) mixed = -1.0f;
byte outputSample = (byte) (mixed * 128.0f);
data3[i] = outputSample;
}
audioTrack.write(data3, 0, count);
}
L.m("Thread completed");
audioTrack.stop();
audioTrack.release();
dataInputStream.close();
fileInputStream.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
rawaudioisRunning = false;
} catch (IOException e) {
e.printStackTrace();
rawaudioisRunning = false;
}