我正在播放音频(mySound)作为背景音乐。单击按钮时,应停止背景音频,并开始播放不同的音频(mySound11)。完成此音频后,背景音乐应自动从其离开的位置恢复。我已经尝试过这段代码,但是在mySound11结束后,后台音频还没有恢复。请帮忙。提前谢谢。
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();
}
<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" />
答案 0 :(得分:0)
我在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();
}
}
}