Android: How to Create Fade-In/Fade-Out Sound Effects for Any Music File That My App Plays

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

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.

Android Studio Mediaplayer how to fade in and out

Looking at the linked example, you would have to call fadeIn()/fadeOut() in a loop, to increase/decrease the volume over a period of time. deltaTime would be the time between each iteration of the loop.

You'd have to do this in a separate thread from your main UI thread, so you don't block it and cause your app to crash. You can do this by either putting this loop inside a new Thread/Runnable/Timer.

Here is my example for fading in (you can do a similar thing for fading out):

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;

}

Instead of using two separate MediaPlayer objects, I would in your case use just one and swap the track between the fades.
Example:

**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**

Hope this solves your problem.

how to get the sound fade in functionality in alarm application using media player in android

you can use this method:

setVolume(float leftVolume, float rightVolume);

to create "fade in" effect you'll just start at zero and keep setting it a little bit higher at regular intervals. Some thing like this will increast the volume by 5% every half of a second

            final Handler h = new Handler();
float leftVol = 0f;
float rightVol = 0f;
Runnable increaseVol = new Runnable(){
public void run(){
mp.setVolume(leftVol, rightVol);
if(leftVol < 1.0f){
leftVol += .05f;
rightVol += .05f;
h.postDelayed(increaseVol, 500);
}
}
};

h.post(increaseVol);

you can control how much it gets raised each tick by changing what you add to leftVol and rightVol inside the if statement. And you can change how long each tick takes by changing the 500 parameter in the postDelayed() method.

Fade Volume on Button Click

Create a While loop to control the volume fade In and fade Out:

Screenshot

How to create a fade out button

The difference between

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

and the code that you posted, is that you set the volume directly to 1, and ignore the volume variable that you're changing. Instead use the volume variable exactly as they do in the solution to the other question. This also needs to be called several times via a timer.

deltatime should be the amount of time that passed since the last time the method was called. This is to keep the fade consistent if the phone lags or something.

HTA. how to fade-out the embedded music mp3 (reload)

Using the answer in the duplicate link, I made some adjustments to eliminate an IndexSizeError, play the mp3 without a button, and make the fade last a reasonable amount of time. Since your sample code starts off in VBScript, I've assumed that's your preferred language. If not, I can post a JScript version as well.

Note: What makes this, perhaps, not a duplicate is that, for an HTA, the document mode must be declared and set to IE=9 or higher.

Note: Document mode IE=9 and higher are much more case sensitive. For example, screen.availWidth will work, screen.AvailWidth will throw an error.

<!DOCTYPE html>
<html>
<head>
<title>Fade Test</title>
<meta charset="UTF-8" http-equiv="X-UA-Compatible" content="IE=9">
<hta:application
id=oHTA
icon=SndVol.exe
>
<script language="vbscript">
Set oWSH = CreateObject("Wscript.Shell")
Set oFSO = CreateObject("Scripting.FileSystemObject")

w = 350
h = 90
window.resizeTo w, h
window.moveTo (screen.availWidth - w)/2, (screen.availHeight - h)/2

MyPath = Mid(document.URL,8)
MyFolder = oFSO.GetParentFolderName(MyPath)
oWSH.CurrentDirectory = MyFolder

Sub window_onLoad
mp3.play
FadeOut
End Sub

Sub FadeOut
If mp3.volume >= 0.1 Then
mp3.volume = mp3.volume - 0.1
window.setTimeout "FadeOut()", 2000
Else
self.close
Exit Sub
End If
End Sub

</script>
<style>
</style>
</head>
<body>
<audio id="mp3">
<source src="./LZ.mp3" type='audio/mp4'>
</audio>
</body>
</html>

fade in and out music while speaking a text

I finally got something that is working. Not perfect though. A quite dirty trick. Just in case it can help to someone:

This is fixed on API 8 with requestAudioFocus and abandomAudioFocus methods of AudioManager.

But for former versions, you can try this. Play TTS through a different stream channel, let's say STREAM_NOTIFICATIONS. Then you just need to return audio focus to STREAM_MUSIC. How can you achieve that?. Sending a silence string (" ") to TTS but this time through STREAM_MUSIC. The effect will be: music is stopped, your TTS message gets spoken, and finally your music is back after the voice alert. Not nice or something to feel proud of, but... if someone knows of a different way, i will appreciate it



Related Topics



Leave a reply



Submit