如何使mediaPlayer停止

如何使mediaPlayer停止

本文介绍了当另一个mediaPlayer启动时,如何使mediaPlayer停止,以使它们不会在彼此之上播放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个按钮都可以播放mp3.当播放第一首歌曲时,我希望单击第二首歌曲以停止播放第一首歌曲,然后开始播放被单击的歌曲.同样,如果按两次第一个按钮,则第二次重置歌曲.

I have 2 buttons that both play an mp3. When the first song is playing I want a click of the second song to stop the first song, and start the song that was clicked. also if the first button is pressed twice the second press resets the song.

基本上,我不希望在按下多个按钮时将歌曲彼此叠加播放.

basically I don't want the songs to play on top of each other when multiple buttons are pressed.

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.placeyouknow:
    String url = "http://www.katastro.com/audio/facts/01%20That%20Place%20You%20Know.mp3";
    mp = new MediaPlayer();

try {
    mp.setDataSource(url);
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mp.prepare();
    mp.start();

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    case R.id.fallen:
    String url1 = "http://www.katastro.com/audio/fallen/01%20Fallen.mp3";
    mp = new MediaPlayer();

try {
    mp.setDataSource(url1);
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mp.prepare();
    mp.start();

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

推荐答案

Whoooaaaaa,失去了MediaPlayer左右的句柄.

Whoooaaaaa, losing handles on MediaPlayers left and right.

首先,对于此特定活动,您只应放置

First of all, for this particular activity, you should only put

mp = new MediaPlayer();

您活动的onCreate()方法中的

.删除在onClick()方法中调用的两个,并将其移至onCreate()方法.

in the onCreate() method of your activity. Delete the two you call in the onClick() method and move it to the onCreate() method.

从那里开始,您要做的就是在调用mp.setDataSource()之前包含对mp.reset()的调用,它应该像您希望的那样工作!

From there, all you have to do is include a call to mp.reset() right before you call mp.setDataSource() and it should work just like you want it to!

欢呼

这篇关于当另一个mediaPlayer启动时,如何使mediaPlayer停止,以使它们不会在彼此之上播放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 23:17