添加发布方式(MediaPlayer)后,应用无法运行

时间:2018-07-05 14:56:40

标签: android android-mediaplayer

我是android的初学者,正在创建一个仅播放一首歌曲并包含3种开始,暂停和停止歌曲选项的android应用。在添加应用程序播放的释放方法之前,暂停了歌曲,在添加释放按钮之后,应用程序甚至无法播放歌曲。

下面是XML代码    

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
    android:id="@+id/start_button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start song 1"
    />
<Button
    android:id="@+id/pause_button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="pause song 1"
    />
<Button
    android:id="@+id/stop_button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="stop song 1"

    />

和Java代码

package com.example.android.musicplayer;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private void releaseMediaPlayer()
{
    if(mediaPlayer!=null)
        mediaPlayer.release();
    mediaPlayer=null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.song);
    Button startButton = (Button) findViewById(R.id.start_button1);
    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            releaseMediaPlayer();
            mediaPlayer.start();
        }
    });
    Button pauseButton = (Button) findViewById(R.id.pause_button1);
    pauseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mediaPlayer.pause();
        }
    });

    Button stopButton = (Button) findViewById(R.id.stop_button1);
    stopButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mediaPlayer.stop();


        }
    });
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
          releaseMediaPlayer();
}

});
}
}

0 个答案:

没有答案