【问题标题】:MediaPlayer stops playing when button is clicked单击按钮时 MediaPlayer 停止播放
【发布时间】:2017-12-11 22:47:34
【问题描述】:

我制作了一个游戏应用程序。我希望一首歌只在主要游戏过程中播放。我在游戏活动中启动了 MediaPlayer。然后在游戏的片段中,只要点击一个按钮,歌曲就会停止。即使单击按钮,我也希望音乐继续播放。

游戏活动:

@Override
protected Fragment createFragment() {
    return GameFragment.newInstance();
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.quit:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setCancelable(false);
            builder.setMessage("Are you sure you want to quit this game?");
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            builder.setNegativeButton("No",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
            return true;
        case R.id.music_switch:
            MediaPlayer mp = MediaPlayer.create(this, R.raw.music);
            if (mp.isPlaying())
                mp.stop();
            else
                mp.start();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

片段的 onClickListener 中是否有我必须放入的内容?

【问题讨论】:

    标签: java android android-fragments


    【解决方案1】:

    如果您检查状态并且它正在播放,您可以调用暂停命令。使用该类时请完全参考此状态图,因为它使一切变得更容易。您会注意到,从停止开始就没有返回的路径。相反,您需要先准备()然后开始()。

    【讨论】:

      【解决方案2】:

      您是否尝试过注释掉 mp.stop() 行?

      if (mp.isPlaying())
          mp.stop(); // <--- here
      else
          mp.start();
      return true;
      

      【讨论】:

      • 是的,我认为问题是,当与片段交互时,活动被中断
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      相关资源
      最近更新 更多