Reputation: 1283
i want to play a sound for 5 seconds but the code which i am using is playing the sound infinitely.
My code is
final MediaPlayer player = new MediaPlayer();
AssetFileDescriptor afd = this.getResources().openRawResourceFd(R.raw.hangout_ringtone);
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
player.setAudioStreamType(AudioManager.STREAM_ALARM);
player.setLooping(true);
player.prepare();
Upvotes: 0
Views: 3011
Reputation: 6492
Create a new handler to post a delay for when to stop.
mMediaPlayer.start();
// wait 5 sec... then stop the player.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mMediaPlayer.stop();
}
}, 5000);//millisec.
Upvotes: 1
Reputation: 10014
Use a Runnable with a delay to stop your audio.
postDelayed(new Runnable() {
public void run() {
//Code to stop your sound
}
}, 5000);
Upvotes: 2