Search code examples
androideffectsaudio-playersoundeffect

Android: How to create fade-in/fade-out sound effects for any music file that my app plays?


The application that I am working on plays music files. If a timer expires I want the music to fade out. How do I do that. I am using MediaPlayer to play music and music files are present in raw folder of my application.


Solution

  • One way to do it is to use MediaPlayer.setVolume(right, left) and have these values decrement after every iteration..here is a rough idea

    float volume = 1;
    float speed = 0.05f;
    
    public void FadeOut(float deltaTime)
    {
        mediaPlayer.setVolume(volume, volume);
        volume -= speed* deltaTime
    
    }
    public void FadeIn(float deltaTime)
    {
        mediaPlayer.setVolume(volume, volume);
        volume += speed* deltaTime
    
    }
    

    The FadeIn() or FadeOut() should be called once this timer of yours has expired. The method doesn't need to take the deltaTime, but it's better as it will lower the volume at the same rate across all devices.