为什么在尝试暂停音频时暂停按钮不起作用?

时间:2021-03-07 09:38:45

标签: android

暂停按钮不起作用。 我正在尝试导入音频,然后播放和暂停它。但尽管如此,代码还是无法运行。

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;


public class MainActivity extends AppCompatActivity {

MediaPlayer mediaPlayer;

public void play(View view){
    mediaPlayer.start();
}
 public void pause(View view){
    mediaPlayer.pause();
}

这里我添加了这个暂停媒体播放器。仍然,此按钮不起作用

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mediaPlayer =MediaPlayer.create(this, R.raw.bensound_energy);

 }
}

这是我的 .XML 布局

 <?xml version="1.0" encoding="utf-8"?>
 <androidx.constraintlayout.widget.ConstraintLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="pause"
tools:context=".MainActivity">

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="159dp"
    android:layout_marginLeft="159dp"
    android:layout_marginTop="213dp"
    android:layout_marginEnd="159dp"
    android:layout_marginRight="159dp"
    android:onClick="play"
    android:text="PLAY"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="162dp"
    android:layout_marginLeft="162dp"
    android:layout_marginTop="41dp"
    android:layout_marginEnd="157dp"
    android:layout_marginRight="157dp"
    android:layout_marginBottom="381dp"
    android:text="PAUSE"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button" />
   </androidx.constraintlayout.widget.ConstraintLayout>

2 个答案:

答案 0 :(得分:0)

我认为您的暂停按钮不起作用,因为您忘记像这样将 pause() 方法放入暂停按钮中

Error- The method readerFor(Class<Map>) is undefined for the type CsvMapper. 

答案 1 :(得分:0)

使用此代码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaPlayer =MediaPlayer.create(this, R.raw.bensound_energy);
        Button button2 = findViewById(R.id.button2);
        
        button2.setOnclickListener v-> {
        if(mPlayer.isPlaying()){
        mediaPlayer.pause();
        } else {
        mediaPlayer.start();
         }
  
       }
      }
    }