生成特定頻率的音調
要播放具有特定音調的聲音,我們首先必須建立正弦波聲音。這是通過以下方式完成的。
final int duration = 10; // duration of sound
final int sampleRate = 22050; // Hz (maximum frequency is 7902.13Hz (B8))
final int numSamples = duration * sampleRate;
final double samples[] = new double[numSamples];
final short buffer[] = new short[numSamples];
for (int i = 0; i < numSamples; ++i)
{
samples[i] = Math.sin(2 * Math.PI * i / (sampleRate / note[0])); // Sine wave
buffer[i] = (short) (samples[i] * Short.MAX_VALUE); // Higher amplitude increases volume
}
現在我們必須配置 AudioTrack 以根據生成的緩衝區進行播放。它以下列方式完成
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, buffer.length,
AudioTrack.MODE_STATIC);
寫入生成的緩衝區並播放軌道
audioTrack.write(buffer, 0, buffer.length);
audioTrack.play();
希望這可以幫助 :)