Rameel Hashmi
Rameel Hashmi

Reputation: 11

Double sound android

package project.kalmas;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;

public class one extends Activity {

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one);
    }

    public void onclick2(View view)
    {
        Intent i=new Intent("project.two");
        startActivity(i);
    }
    public void onclick3(View view)
    {
        MediaPlayer mp= MediaPlayer.create(this,R.raw.one);
        if(mp.isPlaying()){
            mp.stop();
        } else {
            mp.start();
        }

    }

} When i click button it play sound then again i click button to stop it wont stop and play sound again which results in double sound playing at one time.Please help

Upvotes: 0

Views: 981

Answers (1)

Vince Blas
Vince Blas

Reputation: 81

You are creating a new MediaPlayer with every click, instead of keeping a reference to the first one. The MediaPlayer that is playing the sound is different than the MediaPlayer that you are calling isPlaying() on. You need to turn the mp variable into a field so you can keep a reference to it.

I imagine something like this would work:

public class one extends Activity {

    MediaPlayer mp;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one);
        mp = MediaPlayer.create(this,R.raw.one);
    }

    public void onclick2(View view)
    {
        Intent i=new Intent("project.two");
        startActivity(i);
    }
    public void onclick3(View view)
    {

        if(mp.isPlaying()){
            mp.stop();
        } else {
            mp.start();
        }

    }
}

Upvotes: 1

Related Questions