yasserbn
yasserbn

Reputation: 391

Duration of a generated audio sine wave

I am trying to generate 5 seconds of sine wave sound with frequency 1000. I have written the following code

int sampleRate = 44100;
int freqOfTone = 1000;
AudioTrack track;
// 5 seconds
short samples = new short[sampleRate*5];
track = new AudioTrack(AudioManager.STREAM_MUSIC,
         sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                      AudioFormat.ENCODING_PCM_16BIT, samples.length,
                                      AudioTrack.MODE_STATIC);

double angle = 0;
double increment = (2 * Math.PI * freqOfTone / sampleRate); // angular increment 

for (int i = 0; i < samples.length-1; i++) {
          samples[i] =   (short) (Math.sin(angle) * Short.MAX_VALUE);
          angle += increment;
    }
track.write(samples, 0, samples.length); // write data to audio hardware 
track.play(); 

The sound wave length is only 2.5 seconds and I think it should be 5 seconds. Why?

Upvotes: 2

Views: 1557

Answers (3)

kngtrr
kngtrr

Reputation: 31

See the reference.

The 5th argument of AudioTrack constructor is "bufferSizeInBytes".

Upvotes: 2

iTech
iTech

Reputation: 18460

This seems to be the correct behavior because you specified a ENCODING_PCM_16BIT, if you change it to ENCODING_PCM_8BIT you will get 5 seconds of play.

Upvotes: 0

Yimin Rong
Yimin Rong

Reputation: 2027

Is track.play(); synchronous or asynchronous? If the latter, you may be ending the program and shutting it down before it gets a chance to finish. You can try a "press any key" or other pause at the end to confirm.

Upvotes: 0

Related Questions