gpt4 book ai didi

android - 如何以16位格式分别在左右声道上播放两个正弦波?

转载 作者:行者123 更新时间:2023-12-03 02:15:10 25 4
gpt4 key购买 nike

我需要生成2个具有不同频率的正弦波音调,然后分别在Android立体声模式下将它们分别播放到左右声道中。

这是我的代码:

int sample;
double sampleRate;
double duration;
double time;
double f1;
double f2;
double amplitude1;
double amplitude2;
double sineWave1;
double sineWave2;
float[] buffer1;
float[] buffer2;
byte[] byteBuffer1;
byte[] byteBuffer2;
byte[] byteBufferFinal;
int bufferIndex;
short x;
short y;
AudioTrack audioTrack;

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

sampleRate = 44100.0;
duration = 20.0;
f1 = 440.0;
amplitude1= 1;
f2 = 444.0;
amplitude2 = 0;

buffer1 = new float[(int)(duration*sampleRate)];
buffer2 = new float[(int)(duration*sampleRate)];

for(sample = 0; sample < buffer1.length; sample ++){
time = sample / sampleRate;
buffer1[sample] = (float)(amplitude1*Math.sin(2*Math.PI*f1*time));
buffer2[sample] = (float)(amplitude2*Math.sin(2*Math.PI*f2*time));
}

byteBuffer1 = new byte[buffer1.length*2]; //two bytes per audio frame, 16 bits

for(int i = 0, bufferIndex=0; i < byteBuffer1.length; i++){
x = (short) (buffer1[bufferIndex++]*32767.0); // [2^16 - 1]/2 = 32767.0
byteBuffer1[i] = (byte) x; // low byte
byteBuffer1[++i] = (byte) (x >>> 8); // high byte
}


byteBuffer2 = new byte[buffer2.length*2];

for(int j = 0, bufferIndex=0; j < byteBuffer2.length; j++){
y = (short) (buffer2[bufferIndex++]*32767.0);
byteBuffer2[j] = (byte) y; // low byte
byteBuffer2[++j] = (byte) (y >>> 8); // high byte

}

byteBufferFinal = new byte[byteBuffer1.length*2];
//LL RR LL RR LL RR
for(int k = 0, index = 0; index < byteBufferFinal.length - 4; k=k+2){
byteBufferFinal[index] = byteBuffer1[k]; // LEFT {0,1/4,5/8,9/12,13;...}
byteBufferFinal[index+1] = byteBuffer1[k+1];
index = index + 2;
byteBufferFinal[index] = byteBuffer2[k]; // RIGHT {2,3/6,7/10,11;...}
byteBufferFinal[index+1] = byteBuffer2[k+1];
index = index + 2;
}

audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
(int) sampleRate,AudioFormat.CHANNEL_OUT_STEREO,
AudioFormat.ENCODING_PCM_16BIT,byteBufferFinal.length,
AudioTrack.MODE_STATIC);

audioTrack.write(byteBufferFinal, 0, byteBufferFinal.length);
audioTrack.play();
}

输出缓冲区(byteBufferFinal)具有16位格式:LL RR LL RR LL LL RR LL(其中每个字符为1个字节)

我的代码在左右声道中的声音分配效果不佳。我证明它在“1”中留下一个振幅,在“0”中留下另一个振幅,这样使得2个声道中的1个没有声音,但是都发出声音

我的代码有什么问题?

最佳答案

我使用在三星S4上运行的API 18(Eclipse Kepler)进行了尝试,并且运行良好。右声道静音,左声道播放440Hz正弦波。

我在阅读代码时注意到的唯一错误是播放的持续时间是应播放的持续时间的1/2:“byteBufferFinal = new byte [buffer1.length * 2];”行而是应为“byteBufferFinal =新的byte [byteBuffer1.length * 2];”

可悲的是,问题可能出在您的音频线或扬声器上:音频插头可能没有完全插入电话插孔,从而使两个扬声器都播放一个 channel 。

关于android - 如何以16位格式分别在左右声道上播放两个正弦波?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20461243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com