简体   繁体   English

无法让媒体播放器播放mp3

[英]Can't get media player to play mp3

Can anyone tell me why this code doesn't work? 谁能告诉我为什么此代码不起作用? It compiles but when I click on the button nothing plays and then it crashes. 它可以编译,但是当我单击该按钮时,没有任何动作,然后崩溃。 I'm a noob =[ 我是菜鸟= [

public class MainActivity extends ActionBarActivity {

private MediaPlayer newTune;
    public void playB(View paramView) throws IOException {
    newTune = MediaPlayer.create(this, R.raw.b);

    if (newTune.isPlaying()) {
        // newTune.stop();
    } else {
        newTune.prepare();
        newTune.start();
    }
}

There are a couple of problems I can see. 我可以看到几个问题。

1.) You don't need to call prepare() , as create() has already taken care of this for you. 1.)您不需要调用prepare() ,因为create()已经为您解决了这一问题。

2.) newTune.isPlaying() is always going to be false, as you've just created a new MediaPlayer. 2.) newTune.isPlaying()始终为false,因为您刚刚创建了一个新的MediaPlayer。

From the docs: 从文档:

http://developer.android.com/reference/android/media/MediaPlayer.html http://developer.android.com/reference/android/media/MediaPlayer.html

MediaPlayer.onCreate() ... MediaPlayer.onCreate() ...

Convenience method to create a MediaPlayer for a given resource id. 为给定资源ID创建MediaPlayer的便捷方法。 On success, prepare() will already have been called and must not be called again. 成功后,将已经调用prepare(),并且不能再次调用。

Try something like this: 尝试这样的事情:

public class MainActivity extends ActionBarActivity {

private MediaPlayer newTune;
    public void play() {
    newTune = MediaPlayer.create(this, R.raw.b);

    newTune.start();
    }
}

Here's a simple example of a better way of handling the whole thing: 这是处理整个事情的更好方法的简单示例:

public class MainActivity extends Activity {

    private MediaPlayer mMediaPlayer;
    private boolean mIsPrepared;

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

        mMediaPlayer = MediaPlayer.create(this, R.raw.raw1);
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mIsPrepared = true;
            }
        });

        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playOrPause();
            }
        });
    }

    public void playOrPause() {
        if (mMediaPlayer == null || !mIsPrepared) {
            return;
        }
        if (!mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
        } else {
            mMediaPlayer.pause();
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM