我成功地将两个8位文件与下面的代码混合在一起。(使用已编译的Musicg 1.4.2.0 jar lib)但是当我尝试混合两个22050(采样率)和16位文件时,生成的文件播放速度更快。尝试了标题代码或混合方程式中的所有内容,但仍然可以更快地播放(可能两次)。试图改变128到35768(2 ^到2 ^ 15),但我注意到它与振幅有关,长度保持不变。所以它继续玩得更快。 有什么建议吗?
InputStream in1 = getResources().openRawResource(R.raw.myfile);
InputStream in2 = getResources().openRawResource(R.raw.myfile2);
Wave w1 = new Wave(in1);
short[] music1 = w1.getSampleAmplitudes();
in1.close();
Wave w2 = new Wave(in2);
short[] music2 = w2.getSampleAmplitudes();
in2.close();
byte[] output = new byte[(music1.length > music2.length) ? music2.length
: music1.length];
for (int i = 0; i < output.length; i++) {
float samplef1 = music1[i] / 32768.0f; // 2^7=128
float samplef2 = music2[i] / 32768.0f;
float mixed = (samplef1 + samplef2)/2;
//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;
} // for loop
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+"result.wav");
if (f.exists()) {
f.delete();
}
FileOutputStream fo = new FileOutputStream(f);
WaveHeader wh = w2.getWaveHeader();
MyWaveHeader mwh = new MyWaveHeader((short) wh.getAudioFormat(),
(short) wh.getChannels(), wh.getSampleRate(),
(short) wh.getBitsPerSample(), output.length);
mwh.write(fo);
fo.write(output);
fo.flush();
fo.close();
// MusicPlayer
MediaPlayer mp = new MediaPlayer();
// Listeners
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
}); // Important
mp.reset();
mp.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+"birdbellhigh.wav");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
mp.start();
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
22050, AudioFormat.CHANNEL_OUT_DEFAULT,
AudioFormat.ENCODING_PCM_16BIT, output.length,
AudioTrack.MODE_STREAM);
audioTrack.play();
audioTrack.write(output, 0, output.length);