MediaPlayer不会停止或暂停

时间:2018-06-30 04:23:40

标签: android android-mediaplayer

我正在尝试制作一个简单的应用程序,以帮助我学习如何为Android编写代码。应用程序的原理很简单:当您按下按钮时,它将开始播放声音文件。释放按钮时,音频停止。按下按钮可以工作,但不能释放。提前致谢!这是我的Java代码:

package com.example.siriu.presstoplay;

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


public class MainActivity extends AppCompatActivity {
private MediaPlayer mp;

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

    Button button = findViewById(R.id.pressbutton);
    button.setOnTouchListener(handleTouch);
    mp = MediaPlayer.create(this, R.raw.test);

}


private View.OnTouchListener handleTouch = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                    Log.d("button", "down");
                    play();
                break;
            case MotionEvent.ACTION_UP:
                Log.d("button", "up");
                pause();
                break;
        }

        return true;
    }
};

public void play (){
    final MediaPlayer mp = MediaPlayer.create(this, R.raw.test);
    mp.start();
    Log.d("MediaPlayer", "started");
}

public void pause (){
    mp.stop();
    Log.d("MediaPlayer", "paused");
}

}

1 个答案:

答案 0 :(得分:0)

  

Android MediaPlayer不会停止或暂停

因为在您的play ()方法中,您正在启动MediaPlayer方法的本地声明的play () 并在您的pause ()中尝试停止声明为全局的MediaPlayer

  

在这种情况下,您的全局声明MediaPlayer mp;尚未开始

尝试一下

从您的final MediaPlayer mp = MediaPlayer.create(this, R.raw.test);方法中删除play()

public void play (){

    mp.start();
    Log.d("MediaPlayer", "started");
}