开发者

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

开发者 https://www.devze.com 2023-04-01 08:20 出处:网络
Hi i am new to android. I am developing a application with alarm functionality. Here i need to provide the sound fade in functionality. I am using media player to invoke the ringtone for alarm. here i

Hi i am new to android. I am developing a application with alarm functionality. Here i need to provide the sound fade in functionality. I am using media player to invoke the ringtone for alarm. here is my code for playing alarm sound

 try {
                        if(mp==null){
                System.out.println("-------mp is null now------------");
                Uri myUri = Uri.parse("android.resource://com.android.crazy/raw/airtel");
           mp=MediaPlayer.create(Alarm.this, myUri);
            }
mp.setDataSource(songName);
            mp.prepareAsync();
            mp.setLooping(true);

        } catch (Exception e) {
            e.printStackTrace();
        } 
      mp.start();

Here i need to give the sound fadein functionality. please advise me how to put the sound fade in for a particular amount of time like 开发者_JAVA技巧5 mins

Thanks in advance


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.


I revised @FoamyGuy's answer to avoid compiler and runtime errors and for brevity and clarity:

// (At this point mp has been created and initialized)
public float mpVol = 0f;
mp.setVolume(mpVol, mpVol);
mp.start();

final Handler h = new Handler();
h.post(new Runnable() {
    public void run() {
        if (mp.isPlaying()) {
            if (mpVol < 1.0f) {
                mpVol += .05f;
                mp.setVolume(mpVol, mpVol);
                h.postDelayed(this, 500);
            }
        }
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消