Android Studio Mediaplayer如何淡入淡出

olo*_*p01 8 audio android timedelta media-player

我正在使用android studio中的mediaplayer类.我只想淡出一个声音并淡化另一个声音,而不是使用setVolume(0,0)和setVolume(1,1).

我为此创建了两个媒体播放器,似乎我在这个帖子中找到了一个解决方案:Android:如何为我的应用播放的任何音乐文件创建淡入/淡出音效?但我不知道如何使用deltaTime.

还有其他一些解决方案,我几乎无法理解.难道没有一种简单的方法来淡化两个媒体播放器,我无法想象还没有人需要这个或者每个人都使用强迫性代码来实现它.我该如何使用deltaTime?

ak9*_*k93 10

查看链接的示例,您必须在循环中调用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;

}
Run Code Online (Sandbox Code Playgroud)

在你的情况下,我会使用一个并在渐变之间交换轨道,而不是使用两个单独的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**
Run Code Online (Sandbox Code Playgroud)

希望这能解决你的问题.