查看鏈接的example,您必須在循環中調用fadeIn()/ fadeOut()以在一段時間內增加/減少音量。 deltaTime將是循環的每次迭代之間的時間。
您必須在與主UI線程分開的線程中執行此操作,因此您不會阻止它並導致應用程序崩潰。你可以通過把這個循環放入一個新的Thread/Runnable/Timer中來完成。
這裏是我的衰落(你可以做淡出了類似的事情),例如:
int volume = 0;
private void startFadeIn(){
final int FADE_DURATION = 3000; //The duration of the fade
//The amount of time between volume changes. The smaller this is, the smoother the fade
final int FADE_INTERVAL = 250;
final int MAX_VOLUME = 1; //The volume will increase from 0 to 1
int numberOfSteps = FADE_DURATION/FADE_INTERVAL; //Calculate the number of fade steps
//Calculate by how much the volume changes each step
final float deltaVolume = MAX_VOLUME/(float)numberOfSteps;
//Create a new Timer and Timer task to run the fading outside the main UI thread
final Timer timer = new Timer(true);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
fadeInStep(deltaVolume); //Do a fade step
//Cancel and Purge the Timer if the desired volume has been reached
if(volume>=1f){
timer.cancel();
timer.purge();
}
}
};
timer.schedule(timerTask,FADE_INTERVAL,FADE_INTERVAL);
}
private void fadeInStep(float deltaVolume){
mediaPlayer.setVolume(volume, volume);
volume += deltaVolume;
}
而不是使用兩個單獨的MediaPlayer對象,我會在你的情況下,只使用一個和交換軌道淡入淡出之間。 例如:
**Audio track #1 is playing but coming to the end**
startFadeOut();
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(context,audiofileUri);
mediaPlayer.prepare();
mediaPlayer.start();
startFadeIn();
**Audio track #2 has faded in and is now playing**
希望這可以解決您的問題。
謝謝,這會有幫助,因爲我還沒有找到其他工作解決方案!此外,在新線程上運行此提示也非常有幫助!謝謝! – olop01