K. *_*esi 10 java android waveform
我正在尝试使用AudioTrack生成正弦波,方波和锯齿波.然而,这个创建的音频听起来并不像纯正弦波,但是它有一些其他的波形覆盖.在第一个例子中使用方法时,我将如何获得纯正弦波,就像在第二个代码示例中那样?由于顶部示例仅围绕第二个中使用的某些算法移动,它们不应该产生相同的波吗?
@Override
protected Void doInBackground(Void... foo) {
short[] buffer = new short[1024];
this.track = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
float samples[] = new float[1024];
this.track.play();
while (true) {
for (int i = 0; i < samples.length; i++) {
samples[i] = (float) Math.sin( (float)i * ((float)(2*Math.PI) * frequency / 44100)); //the part that makes this a sine wave....
buffer[i] = (short) (samples[i] * Short.MAX_VALUE);
}
this.track.write( buffer, 0, samples.length ); //write to the audio buffer.... and start all over again!
}
}
Run Code Online (Sandbox Code Playgroud)
注意:这确实给了我一个纯粹的正弦波:
@Override
protected Void doInBackground(Void... foo) {
short[] buffer = new short[1024];
this.track = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
float increment = (float)(2*Math.PI) * frequency / 44100; // angular increment for each sample
float angle = 0;
float samples[] = new float[1024];
this.track.play();
while (true) {
for (int i = 0; i < samples.length; i++) {
samples[i] = (float) Math.sin(angle); //the part that makes this a sine wave....
buffer[i] = (short) (samples[i] * Short.MAX_VALUE);
angle += increment;
}
this.track.write( buffer, 0, samples.length ); //write to the audio buffer.... and start all over again!
}
}
Run Code Online (Sandbox Code Playgroud)
感谢Martijn:问题是波形在缓冲区中的波长之间被切断了.增加缓冲区大小可以解决第二个示例中的问题.似乎Math.PI*2算法是循环中最密集的算法,因此将该值移动到仅计算一次的外部变量.
尝试通过以下方式优化您的代码
为什么?因为我怀疑缓冲区准备时间太长,导致两个缓冲区推送之间的延迟很大,这可能会导致噪音。