Reputation: 2799
I am trying to play 10s of sound at 600hz but instead I get 600hz for no more then 3 sec. Can someone point out what I'm doing wrong?
int minBuffersize = AudioTrack.getMinBufferSize(samplerate,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT);
int size= (int) ((10f*samplerate)
/minBuffersize +1);
size*=minBuffersize;//round to the nearest minBuffersize multiple so I don't get an error
short[] play= new short[size];
for(int i =0;i<play.length;i++){
float time=(float)i/(float)samplerate;
play[i]=(short) (((float)Short.MAX_VALUE/10f)*Math.sin(
600f
*time
*(2f*Math.PI)));
}
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC,
samplerate,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT,
play.length,
AudioTrack.MODE_STATIC);
int result=at.write(play,0,play.length);
Log.d("!!!", "result: "+result);
at.play();
where the debug line returns
result: 221184
consistently.
note that play.length = 442368.
after some more experimenting the buffer is always half of play.length, but the sound itself only last 3-5 sec, regardless of how big the buffer is.
Upvotes: 2
Views: 2945
Reputation: 342
In the AudioTrack you're using AudioTrack.MODE_STATIC
(for short sounds with low-latency requirements) while you should use AudioTrack.MODE_STREAM
because it's the right one for long buffers (don't know exactly but is probably related with than 3 seconds).
Take a look here : AudioTrack
Just change your code to:
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC,
samplerate,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT,
play.length,
AudioTrack.MODE_STREAM);
And it should work.
Upvotes: 1
Reputation: 449
AudioTrack needs the buffer size in bytes. As a Short uses 2 bytes you should use size * 2 for your buffer size.
Upvotes: 1
Reputation: 2542
I would suggest decoupling the play length from the AudioTrack buffer size. In my experience it works well to just use the min buffer size and then let the large write block until it is completed.
Something else I've noticed that may be impacting this is that audio doesn't play until half of the buffer is filled. It may be possible with a buffer so large in the AudioTrack that it is just taking that half and trying to work through it.
Upvotes: 1