How to change the duration of the audiotrack by an infinite loop?
I understand that I must apply the following line before audioTrack.play()
:
audioTrack.setLoopPoints (0, generatedSnd.length, -1);
For example, I want the duration will be half a second, therefore, the "duration" variable of type "int" isn't valid. To do so I want the sound to play repeatedly and control the time to stop with a Timer.
The code is:
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();
}