0
votes

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();
}
1

1 Answers

0
votes

I solved the problem by using a different approach: The application runs a thread in the background which creates an infinitely long sound. In another thread, the volume of the sound played in the first thread, is set to 1.0 and 0.0 in the specified frequency.