java – Android:正弦波一代

我试图使用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,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,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,samples.length );  //write to the audio buffer.... and start all over again!

            }           
        }

感谢Martijn:问题是波形在缓冲区的波长之间被切断.增加缓冲区大小可以解决第二个例子中的问题.似乎Math.PI * 2算法是循环中最为密集的,所以将该值移动到一个解决所有内容的外部变量.

解决方法

尝试优化您的代码

>增加缓冲区大小
>准备缓冲区一次,并将其重写为输出流(这将需要一些数学计算缓冲区的完美大小,以确保整个正弦波完美匹配).

为什么?因为我怀疑缓冲区要花很长的时间准备,这是什么原因导致两个缓冲区之间的滞后大,这可能是造成噪音.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...