我正在制作一个android studio apk,在更改活动时,我希望淡出Mediaplayer中播放的歌曲,但它等待淡出结束,然后再转到下一个活动。我如何同时淡出和活动过渡?
float volume = 1f;
while (volume > 0f) {
MainActivity.mediaPlayer.setVolume(volume, volume);
volume = volume - 0.1f;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
MainActivity.mediaPlayer.stop();
答案 0 :(得分:0)
我抬起头来,找到了解决方法
private void fadeOut(final MediaPlayer mPlayer, final int duration) {
final float deviceVolume = getDeviceVolume();
Handler h = new Handler();
h.postDelayed(new Runnable() {
private float time = duration;
private float volume = 0.0f;
@Override
public void run() {
if (!mPlayer.isPlaying()){
mPlayer.start();
time -= 100;
volume = (deviceVolume * time) / duration;
mPlayer.setVolume(volume, volume);
}
if (time > 0){
h.postDelayed(this, 100);
}else {
mPlayer.stop();
}
}
}, 100);
}
}
public static float getDeviceVolume() {
int volumeLevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
return (float) volumeLevel / maxVolume;
}
您可以像这样fadeOut(MainActivity.mediaPlayer,5000);