gpt4 book ai didi

java - Android Studio : Start and Stop audio using mediaPlayer

转载 作者:行者123 更新时间:2023-12-01 18:46:51 25 4
gpt4 key购买 nike

如何使用同一按钮开始停止播放音乐。如果我重复单击下面的代码,则会多次(重叠)播放该歌曲。

另一个问题是在哪里插入 starTimerStopTimer 函数,这样当声音没有播放时,starTimer 将激活,而当声音正在播放时,stopTimer 将激活。

更新的代码:

   public void playFile(View v) {
if (mediaPlayer == null)
mediaPlayer = new MediaPlayer();

try {

mediaPlayer.setDataSource(question.getAudio());

mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(@NotNull MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();

}catch (IOException e) {
e.printStackTrace();
stopSelf();
}

if (mediaPlayer.isPlaying()) {
//pause music
mediaPlayer.pause();
} else {
//play music
mediaPlayer.start();
}
}

XML 文件:

<Button
android:id="@+id/audQuestion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:onClick="playFile"
android:layout_centerInParent="true"/>

以及 startTimer stopTimer 函数

public void starTimer() {
timer = new Timer(Constant.TIME_PER_QUESTION, Constant.COUNT_DOWN_TIMER);
timer.start();
}

public void stopTimer() {
if (timer != null)
timer.cancel();
}

最佳答案

请在全局定义以下代码:

private Button play_pause;
MediaPlayer mediaPlayer;

现在在onCreate方法中:

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

mediaPlayer = new MediaPlayer();
play_pause = findViewById(R.id.play_pause);
}

播放暂停按钮:

play_pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
mediaPlayer.getDuration();
mediaPlayer.start();
}
}
}
});

当音频准备好播放时:

private void readyToPlay(Uri uri) {
try {
if (mediaPlayer != null) {
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setDataSource(activity, uri);//Write your location here
mediaPlayer.prepare();
mediaPlayer.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

音频完成后自动停止:

@Override
public void onCompletion(MediaPlayer mp) {
if (mediaPlayer != null) {
mp.stop();
mp.release();
}
}

不要忘记添加这一行:

implements MediaPlayer.OnCompletionListener

关于java - Android Studio : Start and Stop audio using mediaPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59816801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com