Android:正弦波生成

2024-01-21

我正在尝试使用 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!

            }           
        }

注意:这确实给了我一个纯正弦波:

@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!

            }           
        }

感谢 Martijn:问题是波在缓冲区中的波长之间被切断。增加缓冲区大小可以解决第二个示例中的问题。看来 Math.PI * 2 算术是循环中最密集的,因此将该值移至仅计算一次的外部变量可以解决所有问题。


尝试通过以下方式优化您的代码

  1. 增加缓冲区大小
  2. 准备一次缓冲区,然后继续将其重写到输出流(这将需要一些数学计算缓冲区的完美大小,以确保整个正弦波完全适合其中)。

为什么?因为我怀疑缓冲区准备时间太长,导致两个缓冲区推送之间的延迟很大,这可能会导致噪音。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android:正弦波生成 的相关文章

随机推荐