gpt4 book ai didi

java - 如何设置媒体播放器倾斜后连续播放不中断?

转载 作者:行者123 更新时间:2023-12-01 17:38:06 24 4
gpt4 key购买 nike

请问我想知道如何将我的 MediaPlayer 设置为在 Activity 屏幕旋转时连续播放而不停止?我现在面临的挑战是,当播放正在进行时,我碰巧倾斜屏幕,音乐就会停止,并且需要另一个 Action 才能再次播放。

这是在我的 Activity 中播放音乐的部分

// setting up media players

public void play(View v) {
if (player == null) {
//then here, I sent the position of the chosen song in the intent extras.
//the get back the extra
int position = 0;
try{
position=getIntent().getIntExtra("soundfile",0);
}catch (Exception e)
{
e.printStackTrace();
}
String fileToPlay="song_"+position;
player = MediaPlayer.create(this, position);
Toast.makeText(this, "Hymn Tune Playing", Toast.LENGTH_SHORT ).show();
soundSeekBar = (SeekBar) findViewById(R.id.seekBar1);
soundSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
player.seekTo(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
soundSeekBar.setProgress(player.getCurrentPosition());
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.getCurrentPosition();
}
});
player.setLooping(true);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {

}
});
}
player.start();
Toast.makeText(this, "Playing Continues...", Toast.LENGTH_SHORT ).show();
soundThread = new Thread(this);
soundThread.start();
}

public void pause(View v) {
if (player != null) {
player.pause();
Toast.makeText(this, "Hymn Tune Paused", Toast.LENGTH_SHORT ).show();
}
}

public void stop(View v) {
stopPlayer();
}

private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "Hymn Tune Stoped", Toast.LENGTH_SHORT ).show();
}
}

@Override
protected void onStop() {
super.onStop();
stopPlayer();
}

@Override
public void run() {
int currentPosition = 0;
int soundTotal = player.getDuration();
soundSeekBar.setMax(soundTotal);
while (player != null && currentPosition < soundTotal){
try {
Thread.sleep(300);
currentPosition = player.getCurrentPosition();
}
catch (InterruptedException soundException){
return;
}
catch (Exception otherException){
return;
}
soundSeekBar.setProgress(currentPosition);
}

}

@Override
public void onPointerCaptureChanged(boolean hasCapture) {

}

最佳答案

您必须将播放代码移至后台服务,因为在倾斜期间 Activity 停止并重新启动时,这些代码将持续运行。在此处查看详细的服务指南

https://developer.android.com/guide/components/services

关于java - 如何设置媒体播放器倾斜后连续播放不中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61010127/

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