如何通过无限循环更改音轨的持续时间?
我知道我必须在之前应用以下行audioTrack.play()
:
audioTrack.setLoopPoints (0, generatedSnd.length, -1);
例如,我希望持续时间为半秒,因此“int”类型的“持续时间”变量无效。为此,我希望声音重复播放并使用计时器控制停止时间。
代码是:
private int duration = 1; // seconds
private int sampleRate = 44100;
private final int numSamples = duration * sampleRate;
private final double sample[] = new double[numSamples];
private double freqOfTone = 261.626; // For example musical note C (Do) is 261.626Hz.
private final byte generatedSnd[] = new byte[2 * numSamples];
final Thread thread = new Thread(new Runnable() {
public void run() {
genTone();
handler.post(new Runnable() {
public void run() {
playSound();
}
});
}
});
thread.start();
}
});
void genTone() {
for (int i = 0; i < numSamples; ++i) {
sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone));
}
// convert to 16 bit pcm sound array
// assumes the sample buffer is normalised.
int idx = 0;
for (final double dVal : sample) {
// scale to maximum amplitude
final short val = (short) ((dVal * 32767));
// in 16 bit wav PCM, first byte is the low order byte
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
}
}
void playSound(){
final AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length,
AudioTrack.MODE_STATIC);
audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();
}