我正在构建一个相当简单的 Android 应用程序(sdk 修订版 14:ICS),它允许用户一次选择两个音频剪辑(都是 RIFF/WAV 格式、小端序、签名 PCM-16 位编码)并将它们组合起来创造新声音的各种方法。我用于这种组合的最基本方法如下:
//...sound samples are read in to memory as raw byte arrays elsewhere
//...offset is currently set to 45 so as to skip the 44 byte header of basic
//RIFF/WAV files
...
//Actual combination method
public byte[] makeChimeraAll(int offset){
for(int i=offset;i<bigData.length;i++){
if(i < littleData.length){
bigData[i] = (byte) (bigData[i] + littleData[i]);
}
else{
//leave bigData alone
}
}
return bigData;
}
然后可以通过 AudioTrack 类播放返回的字节数组:
....
hMain.setBigData(hMain.getAudioTransmutation().getBigData()); //set the shared bigData
// to the bigData in AudioTransmutation object
hMain.getAudioProc().playWavFromByteArray(hMain.getBigData(), 22050 + (22050*
(freqSeekSB.getProgress()/100)), 1024); //a SeekBar allows the user to adjust the freq
//ranging from 22050 hz to 44100 hz
....
public void playWavFromByteArray(byte[] audio,int sampleRate, int bufferSize){
int minBufferSize = AudioTrack.getMinBufferSize(sampleRate,
AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,
minBufferSize, AudioTrack.MODE_STREAM);
int i = 0;
at.play();
at.write(audio, 0, audio.length);
at.stop();
at.release();
for(i=0;i<audio.length;i++){
Log.d("me","the byte value at audio index " + i + " is " + audio[i]);
}
}
使用上面的代码组合和播放的结果接近我想要的(在混合后的声音中仍然可以辨别两个样本),但也有很多裂纹、爆裂声和其他噪音。
那么,三个问题:首先,我是否正确使用了 AudioTrack?其次,AudioTrack 配置中的字节序在哪里考虑?声音本身播放良好,听起来几乎就像我在组合时所期望的那样,因此 RIFF/WAV 格式的小端特性似乎在某个地方传达,但我不确定在哪里。最后,对于有符号的 16 位 PCM 编码,我应该期望看到的字节值范围是多少?我希望从上面的 Log.d(...) 调用中看到 logcat 中的值范围从 -32768 到 32767,但结果往往在 -100 到 100 的范围内(除此之外还有一些异常值)。超过 16 位范围的组合字节值是否可以解释噪声?
谢谢,CCJ
更新:主要感谢 Bjorne Roche 和 William the Coderer!我现在将音频数据读入 short[] 结构,DataInputStream 的字节序是使用 William 的 EndianInputStream (http://stackoverflow.com/questions/8028094/java-datainputstream-replacement-for-endianness) 和组合方法已更改为:
//Audio Chimera methods!
public short[] makeChimeraAll(int offset){
//bigData and littleData are each short arrays, populated elsewhere
int intBucket = 0;
for(int i=offset;i<bigData.length;i++){
if(i < littleData.length){
intBucket = bigData[i] + littleData[i];
if(intBucket > SIGNED_SHORT_MAX){
intBucket = SIGNED_SHORT_MAX;
}
else if (intBucket < SIGNED_SHORT_MIN){
intBucket = SIGNED_SHORT_MIN;
}
bigData[i] = (short) intBucket;
}
else{
//leave bigData alone
}
}
return bigData;
}
具有这些改进的混合音频输出质量非常棒!