简体   繁体   中英

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.

2.) newTune.isPlaying() is always going to be false, as you've just created a new MediaPlayer.

From the docs:

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

MediaPlayer.onCreate() ...

Convenience method to create a MediaPlayer for a given resource id. On success, prepare() will already have been called and must not be called again.

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();
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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