I've written an application that generates a short sound using AudioTrack. The sound is being generated using a sine wave.
If I play the sound 2 or 3 times per second, there is absolutely no problem. But if I increase the rate to 15 hz or more, the application crashes instantly.
I think the problem is that every time the sound plays, a new AudioTrack object will be written with the sine data. But if I generate the sound only once, I can only play it once. If I try to play it a second time, nothing happens.
The class attributes are:
private float duration;
private short[] buffer;
The constructors are:
public SoundGenerator()
{
}
public SoundGenerator(float duration)
{
duration *= 44100;
duration *= 2;
this.duration = duration;
buffer = new short[(int)this.duration];
}
And here's the actual code:
public void generateSound(double frequency, float duration)
{
duration *= 44100;
duration *= 2;
double[] mSound = new double[(int)duration];
for (int i = 0; i < this.buffer.length; i++)
{
mSound[i] = Math.sin((2.0*Math.PI * i/(44100/frequency)));
this.buffer[i] = (short) (mSound[i]*Short.MAX_VALUE);
}
}
public void playGeneratedSound(float volume)
{
AudioTrack generatedSound = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
(int)this.duration, AudioTrack.MODE_STATIC);
generatedSound.setStereoVolume(volume, volume);
generatedSound.write(this.buffer,0,(int)this.duration);
generatedSound.play();
}