Android停止了以前的媒体播放器?

时间:2014-05-15 13:41:04

标签: java android android-mediaplayer togglebutton

我有3个切换按钮。我有它工作,当点击它会发出声音,按钮将切换到"停止"。当声音结束时,它会切换回"播放"如果你点击"停止"在播放时,声音会停止并切换回来。

然而我的问题是,如果我点击两个按钮并且它们都在播放我无法阻止前一个按钮。这是因为我无法访问以前的mediaPlayer当前。这是我目前的尝试,任何帮助都会很棒,谢谢!

@Override
public void onClick(View v) 
    {

    int  soundFile = 0;

    switch (v.getId()) 
    {

    case (R.id.btnSound1):

        soundFile = R.raw.sound1;

    break;
        case (R.id.btnSound2):

        soundFile = R.raw.sound2;

    break;
    case (R.id.btnSound3):

        soundFile = R.raw.sound3;

    break;

   }

    final ToggleButton button = (ToggleButton) findViewById(v.getId()); //gets current button
    MediaPlayer media = (MediaPlayer) button.getTag();                  //gets mediaPlayer object stored in button
    if(button.getTag().equals(null))                          //only runs this once, if the mediaPlayer stored object is null (doesn't exist)
    {
      media = getMedia(soundFile);
      button.setTag(media);            //set the new media object to the buttons tag
      media.start();


     media.setOnCompletionListener(new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp)     //when sound is over
        {
            button.setChecked(true); //set back to play
            mp.release();
        }
    });

    button.setOnCheckedChangeListener(new OnCheckedChangeListener(){           //when clicked
        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) 
        {

            if(button.isChecked())      // if stop toggle clicked
            {
                button.setChecked(true); // set to play
                MediaPlayer media = (MediaPlayer) button.getTag();
                media.release();    //stop the sound
            }

            else if(!button.isChecked()) //if play toggle clicked
            {
                 MediaPlayer media = (MediaPlayer) button.getTag();
             media.start(); //play the sound
             button.setChecked(false); //set to stop

            }

        }
       });

    }


}   

public MediaPlayer getMedia(int sound)
{

    MediaPlayer mediaPlayer = MediaPlayer.create(getBaseContext(), sound);
    mediaPlayer.setVolume(100,100);  //sets the volume to max

    return mediaPlayer;
}

0 个答案:

没有答案