Android: Sine Wave Generation

前端 未结 3 1268
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 10:39

I\'m trying to use AudioTrack to generate sine, square, and sawtooth waves. However, the audio this is creating doesn\'t sound like a pure sine wave, but like it has some kind o

相关标签:
3条回答
  • 2021-02-08 11:19

    None of these anwers fixes the problem. The buffer length should be a multiple of the sample rate, or at least the length of one rotation. Let's break it in ton of variables to show we understand things:

    int sampleRate = 44100;
    int bitsPerChannel = 16;
    int bytesPerChannel = bitsPerChannel / 8;
    int channelCount = 1;
    int bytesPerSample = channelCount * bytesPerChannel;
    int bytesPerRotation = sampleRate * bytesPerSample * (1d / (double) frequency);
    

    Then you can multiply this bytesPerRotation by anything, it won't change a fact: there won't be glitch in the sound.

    0 讨论(0)
  • 2021-02-08 11:22

    Try to optimise your code by

    1. increase buffer size
    2. prepare the buffer once, and keep rewriting it to the output stream (this will require some math calculating the perfect size for the buffer to make sure that the whole sine wave fits perfectly in it).

    Why? Because I suspect the buffer to taking to long to prepare, what causes a lag between two buffer pushes to big, which might be causing the noise.

    0 讨论(0)
  • 2021-02-08 11:35

    The only material difference that I can see in your two code samples is that the equation in your first example contains an integer (I), and therefore you're probably doing integer (not floating-point) arithmetic. This would cause a staircasing effect, adding unwanted harmonics to your waveform.

    I suspect that if you simply cast I to a float in your equation, it will produce a pure sine wave.

    samples[i] 
        = (float) Math.sin( (float)i * ((float)(2*Math.PI) * frequency / 44100));
    
    0 讨论(0)
提交回复
热议问题