Satyajit Das
Satyajit Das

Reputation: 2920

Why does audio in MediaPlayer not loop?

This is the portion of my code:

sound= MediaPlayer.create(getContext(),R.raw.sound);
sound.start();
sound.setLooping(true);

This doesn't loop the audio once it is completed. Then I checked some other solutions previously posted in this site and tried the following:

sound= MediaPlayer.create(getContext(),R.raw.sound);
sound.start();
sound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        mp.seekTo(0);
                        mp.start();
                    }
                });

This also didn't help restarting the audio after it finished once. Anything else I can try?

Upvotes: 1

Views: 395

Answers (2)

Satyajit Das
Satyajit Das

Reputation: 2920

It turns out that the problem was with my emulator (Genymotion) which was not looping. When I tried the apk in my actual android device, it worked fine.

Upvotes: 1

Brian
Brian

Reputation: 944

I think it’s just that you’re starting it, then trying set it to loop. Try it like this instead.

btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mp!=null){
                mp.reset();
                mp.release();
            }
            mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
            mp.setLooping(true);
            mp.start();
        }
    });

Upvotes: 0

Related Questions