swati
swati

Reputation: 1283

how to play a sound for 5 seconds

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

Answers (3)

TouchBoarder
TouchBoarder

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

devmiles.com
devmiles.com

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

Anton
Anton

Reputation: 4403

Try to remove this line from your code

player.setLooping(true);

Upvotes: 3

Related Questions