android studio mediaplayer,Android Studio Mediaplayer如何淡入淡出
查看链接的example,您必须在循环中调用fadeIn()/ fadeOut(),以在一段时间内增加/减少音量. deltaTime将是循环的每次迭代之间的时间.您必须在主UI线程的单独线程中执行此操作,因此您不会阻止它并导致应用程序崩溃.您可以通过将此循环放在新的Thread / Runnable / Timer中来实现.这是我淡入的例子(你可以做一个类似的事情淡出):float volume
查看链接的
example,您必须在循环中调用fadeIn()/ fadeOut(),以在一段时间内增加/减少音量. deltaTime将是循环的每次迭代之间的时间.
您必须在主UI线程的单独线程中执行此操作,因此您不会阻止它并导致应用程序崩溃.您可以通过将此循环放在新的Thread / Runnable / Timer中来实现.
这是我淡入的例子(你可以做一个类似的事情淡出):
float 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**
希望这能解决你的问题.
更多推荐
所有评论(0)