java – Android:正弦波一代

前端之家收集整理的这篇文章主要介绍了java – Android:正弦波一代前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用AudioTrack来产生正弦,平方和锯齿波.然而,这个创造的音频听起来不像是纯正弦波,而是像其他波浪相似.在第二个代码示例中,如何使用第一个例子中的方法,如何获得纯正弦波?由于上面的例子只是围绕第二个运算中使用的一些运算,所以不应该产生相同的波形?
  1. @Override
  2. protected Void doInBackground(Void... foo) {
  3. short[] buffer = new short[1024];
  4. this.track = new AudioTrack(AudioManager.STREAM_MUSIC,44100,AudioFormat.CHANNEL_CONFIGURATION_MONO,AudioFormat.ENCODING_PCM_16BIT,minBufferSize,AudioTrack.MODE_STREAM);
  5. float samples[] = new float[1024];
  6.  
  7. this.track.play();
  8.  
  9. while (true) {
  10. for (int i = 0; i < samples.length; i++) {
  11. samples[i] = (float) Math.sin( (float)i * ((float)(2*Math.PI) * frequency / 44100)); //the part that makes this a sine wave....
  12. buffer[i] = (short) (samples[i] * Short.MAX_VALUE);
  13. }
  14. this.track.write( buffer,samples.length ); //write to the audio buffer.... and start all over again!
  15.  
  16. }
  17. }

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

  1. @Override
  2. protected Void doInBackground(Void... foo) {
  3. short[] buffer = new short[1024];
  4. this.track = new AudioTrack(AudioManager.STREAM_MUSIC,AudioTrack.MODE_STREAM);
  5. float increment = (float)(2*Math.PI) * frequency / 44100; // angular increment for each sample
  6. float angle = 0;
  7. float samples[] = new float[1024];
  8.  
  9. this.track.play();
  10.  
  11. while (true) {
  12. for (int i = 0; i < samples.length; i++) {
  13. samples[i] = (float) Math.sin(angle); //the part that makes this a sine wave....
  14. buffer[i] = (short) (samples[i] * Short.MAX_VALUE);
  15. angle += increment;
  16. }
  17. this.track.write( buffer,samples.length ); //write to the audio buffer.... and start all over again!
  18.  
  19. }
  20. }

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

解决方法

尝试优化您的代码

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

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

猜你在找的Android相关文章