我试图使用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算法是循环中最为密集的,所以将该值移动到一个解决所有内容的外部变量.