媒体播放器停止后无法启动

时间:2014-04-27 16:17:54

标签: java android media-player startup

下面是我的媒体播放器代码。我停下来后不再重新开始。怎么解决这个?即使我在调用start方法之前调用了prepare方法。另外,为什么即使退出程序后音乐也不会停止播放。请指教。

   public class MainActivity extends Activity {

Button play,pause,stop;
CheckBox c1,c2,c3;
MediaPlayer song1,song2,song3;
AlertDialog.Builder builder;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    play=(Button)findViewById(R.id.button1);
    pause=(Button)findViewById(R.id.button2);
    stop=(Button)findViewById(R.id.button3);

    c1=(CheckBox)findViewById(R.id.checkBox1);
    c2=(CheckBox)findViewById(R.id.checkBox2);
    c3=(CheckBox)findViewById(R.id.checkBox3);

    song1=MediaPlayer.create(this, R.raw.finalcountdown);
    song2=MediaPlayer.create(this, R.raw.invincible);
    song3=MediaPlayer.create(this, R.raw.somewhereibelong);

    builder=new AlertDialog.Builder(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void start(View view) throws IllegalStateException, IOException
{
    if(c1.isChecked())
    {
        if(!song1.isPlaying())
        {
            song1.prepare();
            song1.start();
        }
        else{
            song1.start();
        }
    }
    if(c2.isChecked())
    {
        if(!song2.isPlaying())
        {
            song2.prepare();
            song2.start();
        }
        else{
            song2.start();
        }
    }
    if(c3.isChecked())
    {
        if(!song3.isPlaying())
        {
            song3.prepare();
            song3.start();
        }
        else{
            song3.start();
        }
    }
    else{
        builder.setMessage("Please mark a checkbox");
    }
}

public void stop(View view)
{
    if(c1.isChecked())
        song1.stop();
    else if (c2.isChecked())
        song2.stop();
    else if (c3.isChecked())
        song3.stop();
    else
        builder.setMessage("Error message ");
}

public void pause(View view)
{
    if(c1.isChecked())
    {
        song1.pause();
    }
    else if(c2.isChecked())
    {
        song2.pause();
    }
    else if(c3.isChecked())
    {
        song3.pause();
    }
    else
        builder.setMessage("error message");
}

}

2 个答案:

答案 0 :(得分:2)

你需要在stop方法中放入song1.release()并释放其他歌曲的方法。有关详细信息,请参阅媒体播放器的生命周期。 http://developer.android.com/reference/android/media/MediaPlayer.html

答案 1 :(得分:1)

您必须释放播放器OnPause或OnDestroy方法。

@Override
public void onDestroy() {
    if(c1!= null)c1.release();
    else if (c2!= null)c2.release();
    else if (c3!= null)c3.release();
    else
        //something
}