Android Studio Mediaplayer how to fade in and out

前端 未结 3 2188
慢半拍i
慢半拍i 2021-02-20 17:08

I am working with the mediaplayer class in android studio. I simply want to fade out one sound and fade in the other sound instead of using setVolume(0,0) and setVolume(1,1).

3条回答
  •  野的像风
    2021-02-20 17:18

    Here's the fade-out code in case it saves someone some time.

    This also includes a stopPlayer() function to release the MediaPlayer from memory. It's a good practice to do so.

    // Set to the volume of the MediaPlayer
    float volume = 1;
    
    private void startFadeOut(){
    
        // The duration of the fade
        final int FADE_DURATION = 3000;
    
        // The amount of time between volume changes. The smaller this is, the smoother the fade
        final int FADE_INTERVAL = 250;
    
        // Calculate the number of fade steps
        int numberOfSteps = FADE_DURATION / FADE_INTERVAL;
    
        // Calculate by how much the volume changes each step
        final float deltaVolume = volume / 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() {
    
                //Do a fade step
                fadeOutStep(deltaVolume);
    
                //Cancel and Purge the Timer if the desired volume has been reached
                if(volume <= 0){
                    timer.cancel();
                    timer.purge();
                    stopPlayer();
                }
            }
        };
    
        timer.schedule(timerTask,FADE_INTERVAL,FADE_INTERVAL);
    }
    
    private void fadeOutStep(float deltaVolume){
        player.setVolume(volume, volume);
        volume -= deltaVolume;
    }
    
    // Release the player from memory
    private void stopPlayer() {
    
        if (player != null) {
    
            player.release();
            player = null;
        }
    }
    

提交回复
热议问题