如何在Android中创建正弦波

时间:2019-07-11 19:36:28

标签: android android-studio sine-wave

我想在有声音的android上创建一个正弦波。

随着用户触摸屏幕,声波的持续时间以及频率都会增加。

这是我生成特定频率的代码:

private void playSound(double frequency, int duration) {
    // AudioTrack definition
    int mBufferSize = AudioTrack.getMinBufferSize(44100,
            AudioFormat.CHANNEL_OUT_MONO,
            AudioFormat.ENCODING_PCM_8BIT);

    AudioTrack mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
            AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
            mBufferSize, AudioTrack.MODE_STREAM);

    // Sine wave
    double[] mSound = new double[4410];
    short[] mBuffer = new short[duration];
    for (int i = 0; i < mSound.length; i++) {
        mSound[i] = Math.sin((2.0*Math.PI * i/(44100/frequency)));
        mBuffer[i] = (short) (mSound[i]*Short.MAX_VALUE);
    }

    mAudioTrack.setStereoVolume(AudioTrack.getMaxVolume(), AudioTrack.getMaxVolume());
    mAudioTrack.play();

    mAudioTrack.write(mBuffer, 0, mSound.length);
    mAudioTrack.stop();
    mAudioTrack.release();
}

0 个答案:

没有答案