gpt4 book ai didi

android - 单击按钮后播放的音频结束后,从停止处重新开始播放音频

转载 作者:行者123 更新时间:2023-12-03 01:56:02 25 4
gpt4 key购买 nike

我正在播放音频(mySound)作为背景音乐。单击按钮后,背景音频应停止并且应开始播放其他音频(mySound11)。音频完成后,背景音乐应自动从其离开的位置恢复。我已经尝试过此代码,但是mySound11结束后背景音频不会恢复。请帮忙。提前致谢。

MainActivity.java

public class MainActivity extends ActionBarActivity {

MediaPlayer mySound;
MediaPlayer mySound11;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySound11 = MediaPlayer.create(this, R.raw.tiktik);
mySound = MediaPlayer.create(this, R.raw.jhakmaarke);
mySound.setLooping(true);
mySound.start();

}



public void playMusic (View view){
mySound.pause();
mySound11.start();
}


@Override
public void onResume() {
super.onResume();
mySound.start();
}


@Override
protected void onPause() {
super.onPause();
mySound.release();
mySound11.release();
finish();
}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Dabaa be"
android:onClick="playMusic"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="72dp" />

最佳答案

我借助Thread解决了您的问题。
我按照您的意愿对其进行了测试。

int mySound11Duration;
MediaPlayer mySound;
MediaPlayer mySound11;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySound11 = MediaPlayer.create(this, R.raw.tiktik);
mySound = MediaPlayer.create(this, R.raw.jhakmaarke);
mySound.setLooping(true);
mySound.start();

}
public void playMusic(View view) {
if (mySound.isPlaying()) { //check mysound is playing or not
mySound11Duration = mySound11.getDuration();
Thread thread=new Thread() {
@Override
public void run() {
try {
mySound.pause();
int mySoundPausePosition = mySound.getCurrentPosition();//get the time where the song is paused.
mySound11.start();
sleep(mySound11Duration);//sleep method causes the currently executing thread to sleep for specified number of time(miliseconds).
mySound.seekTo(mySoundPausePosition);
mySound.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();

}
}
}

关于android - 单击按钮后播放的音频结束后,从停止处重新开始播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35520777/

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