0

我正在尝试在我的应用程序中播放音乐。单击播放按钮时我可以播放,但单击停止按钮时无法停止音乐,请帮助查看此代码并指出问题。我正在使用 MediaPlayer 的 pause() 来暂停音乐。

public class MainActivity extends Activity implements OnClickListener {

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

    Button btn = (Button)findViewById(R.id.Start);
    btn.setOnClickListener(this);

    Button btn1 =(Button)findViewById(R.id.stop);
    btn1.setOnClickListener(this);

}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    MediaPlayer mp = MediaPlayer.create(this, R.raw.test_cbr);
    switch(v.getId()){
        case R.id.Start:                
            mp.start();
        break;
        case R.id.stop:
            mp.pause();
            Toast.makeText(getApplicationContext(), "Music Paused", Toast.LENGTH_SHORT).show();
        }
    }

     }

我正在使用警报消息。我收到此警报消息,但无法暂停音乐。

4

4 回答 4

1

modify your code somethign like this,

public class MainActivity extends Activity implements OnClickListener {
 MediaPlayer mp =null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   mp = MediaPlayer.create(this, R.raw.test_cbr);  
    Button btn = (Button)findViewById(R.id.Start);
    btn.setOnClickListener(this);

    Button btn1 =(Button)findViewById(R.id.stop);
    btn1.setOnClickListener(this);

}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    switch(v.getId()){
        case R.id.Start:   

            mp.start();
        break;
        case R.id.stop:
           if(mp!=null && mp.isPlaying()){
                mp.pause();
       Toast.makeText(getApplicationContext(), "Music Paused", Toast.LENGTH_SHORT).show();
            }

        }
    }

     }

The problem could be because you are creating a new instance of media player in your onClick each time and so the previous created one will be playing already but where you are trying to stop the one that is created newly.

So assigning it globally and initiating it newly in start button alone should do the job.

于 2013-01-22T06:55:41.660 回答
1

这是因为您MediaPlayer每次点击都会创建一个新实例。

您应该只有一个 a 的实例MediaPlayer

于 2013-01-22T06:56:46.560 回答
0

You are creating new Instance every time of media player.Make it global.

Try this changes in your code.

case R.id.stop:
     if(mp.isPlaying() && mp!=null)
     { 
       mp.pause();
     }
     Toast.makeText(getApplicationContext(), "Music Paused", Toast.LENGTH_SHORT).show();
于 2013-01-22T06:55:37.557 回答
0
switch (whatsong) {

    case 1: 
        if(song1.isPlaying()){
            song1.pause();          
        }
于 2013-01-22T06:56:16.910 回答