音乐播放但不停留在Android上

时间:2014-02-04 18:35:47

标签: android

正如我上面所说的在下面的代码中,当我点击按钮时音乐正在播放但是当我第二次单击按钮时没有暂停并且将再次播放
我能做什么? 请帮帮我

public class AudioPlayer extends Activity implements OnClickListener {
Button playButton;
MediaPlayer player;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
playButton = (Button) this.findViewById(R.id.ButtonPlayStop);
playButton.setOnClickListener(this);
}

public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File sdcard = Environment.getExternalStorageDirectory();
File audioFile = new File(sdcard.getPath() + "/bluetooth/یه سوال دارم مگه.mp3");
player = MediaPlayer.create(this,Uri.fromFile(audioFile));
if(audioFile.exists())
{
if(player.isPlaying()){
    if(player!=null){
        player.pause();
    }
}else{
    // Resume song
    if(player!=null){
        player.start();
    }
}

}
else
{
Builder alert = new AlertDialog.Builder( AudioPlayer.this);
                alert.setTitle("Alert");
                alert.setMessage("فایل دانلود نشده است");
                alert.setPositiveButton("OK", null);
                alert.show();
 }

 }

1 个答案:

答案 0 :(得分:1)

试试这个:

  

将这一点放在Onlick上说Onlick()

player = MediaPlayer.create(this,Uri.fromFile(audioFile));

 if(audioFile.exists())
 {
    if(player!=null)
    {
       if(player.isPlaying())
       {
          player.pause();
       }   
       else
       {
         player.start();
       }
    }
}