如何使用手机的后退按钮和创建的后退按钮终止音乐?

时间:2018-10-01 12:55:39

标签: java android

我在应用中播放音乐时遇到了一些错误。即使我退出应用程序,它也不会停止播放。仅当我按下暂停或终止应用程序时,它才会停止。这是我的音乐代码。我应该怎么做才能停止它。

public void play_brain(View g){

    final MediaPlayer brainMP = new MediaPlayer();
    try {
        brainMP.setDataSource("https://firebasestorage.googleapis.com/v0/b/capstone-katugna-001.appspot.com/o/meditation%20music%201%20minute%20peaceful%20music%201%20minute%20mindfulness%20meditation%201%20minute%20relax%20music%201.mp3?alt=media&token=f34fe7c7-54f1-4645-88cf-5e7a21f401d8");
        brainMP.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });

        brainMP.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    pause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            brainMP.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.pause();
                }
            });
            brainMP.pause();
        }
    });
}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用以下代码:

public class MainActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;
    private Button buttonStartPause;

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

        // Initialize your MediaPlayer object here
        Uri myUri = ....; // initialize Uri here
        MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDataSource(getApplicationContext(), myUri);
        mediaPlayer.prepare();
    }

    buttonStartPause.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (mediaplayer.isPlaying()) {
                mediaplayer.pause();
                // here you can set the play icon to your button
            } else {
                mediaplayer.start();
                // here you can set the pause icon to your button
            }
        }
    });

    // To capture back button's pression you can override onBackPressed() in your Activity:
    @Override
    public void onBackPressed() {
        if (mediaplayer.isPlaying()) {
            mediaplayer.pause();
        }
        super.onBackPressed();  
    }
}