生成特定频率的音调
要播放具有特定音调的声音,我们首先必须创建正弦波声音。这是通过以下方式完成的。
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();
希望这可以帮助 :)