java - 如何在MediaPlayer服务中淡入和淡出音乐

标签 java android audio media-player fade

我正在android studio中处理mediaplayer服务,我想在服务启动/停止时淡入/淡出声音。

我已经尝试过此线程的解决方案:
Android Studio Mediaplayer how to fade in and out
,但该代码似乎不适合我的服务。音乐仅播放一秒钟,然后音乐停止。

BGMPlayer.java(服务)

public class BGMPlayer extends Service {
    private MediaPlayer bgmusic1;
    int volume = 0;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        bgmusic1 = MediaPlayer.create(this, R.raw.bgmusic1);
        bgmusic1.setLooping(true);
        bgmusic1.start();
        FadeIn();

    //we have some options for service
    //start sticky means service will be explicity started and stopped
    return START_STICKY;
}


@Override
public void onDestroy() {
    super.onDestroy();
    bgmusic1.stop();
}

private void FadeIn() {

    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
            Log.d("DEBUG","MUSIC VOLUME IS NOW " + volume);
            //Cancel and Purge the Timer if the desired volume has been reached
            if (volume >= 1f) {
                Log.d("DEBUG","MUSIC VOLUME REACHED 1");
                timer.cancel();
                timer.purge();
            }
        }
    };

    timer.schedule(timerTask, FADE_INTERVAL, FADE_INTERVAL);
}

private void fadeInStep(float deltaVolume) {
    bgmusic1.setVolume(volume, volume);
    volume += deltaVolume;

}

}

Activity.java
    @Override
    protected void onStart() {
        super.onStart();
        //music start
        startService(new Intent(this, BGMPlayer.class));
        Log.d("DEBUG","LoadingScreenStart");
    }
    @Override
    protected void onStop() {
        super.onStop();
        //Stop the music
        stopService(new Intent(this, BGMPlayer.class));
    }

调试日志
04-10 21:15:29.325 6147-6147/com.example.max.curerthegame D/DEBUG: LoadingScreenStart
04-10 21:15:29.643 6147-6183/com.example.max.curerthegame D/DEBUG: MUSIC VOLUME IS NOW 0
04-10 21:15:29.893 6147-6183/com.example.max.curerthegame D/DEBUG: MUSIC VOLUME IS NOW 0
04-10 21:15:32.159 6147-6183/com.example.max.curerthegame D/DEBUG: MUSIC VOLUME IS NOW 0
04-10 21:15:32.410 6147-6183/com.example.max.curerthegame D/DEBUG: MUSIC VOLUME IS NOW 0
04-10 21:15:32.660 6147-6183/com.example.max.curerthegame D/DEBUG: MUSIC VOLUME IS NOW 0
04-10 21:15:34.672 6147-6183/com.example.max.curerthegame D/DEBUG: MUSIC VOLUME IS NOW 0
04-10 21:15:34.927 6147-6183/com.example.max.curerthegame D/DEBUG: MUSIC VOLUME IS NOW 0
04-10 21:15:49.765 6147-6183/com.example.max.curerthegame D/DEBUG: MUSIC VOLUME IS NOW 0

最佳答案

在给定的时间间隔后,可以使用Runnable反复降低音量。

编写函数后调用该函数:musicVolumeF(0.2f);

MediaPlayer music;

//do this in onCreate
music = MediaPlayer.create(getApplicationContext(), R.raw.sunnybike2);
music.start();

Handler ha = new Handler();
Runnable mFadeRun;

Float musicVolumeF = 1.0f;
void musicFader(Float desiredVolume)
{
    mFadeRun = new Runnable() {
        @Override
        public void run() {

        // decrement the float value 
        musicVolumeF = musicVolumeF - 0.02f;

        // so it does not go below 0
        if (musicVolumeF < 0)
            musicVolumeF = 0.0f;

        // set the volume to the new slightly less float value
        music.setVolume(musicVolumeF, musicVolumeF);

        // so it stops if it's at about the desired volume
        // you can change the 20 to make it go faster or slower
        if (musicVolumeF > desiredVolume+0.02)
            ha.postDelayed(mFadeRun,20);


        }
    };
    // postDelayed re-posts the Runnable after the given milliseconds
    ha.postDelayed(mFadeRun,20);

}

关于java - 如何在MediaPlayer服务中淡入和淡出音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49754582/

相关文章:

java - org.apache.kafka.streams.examples.wordcount.WordCountDemo 不会终止

java - 是否可以在不需要播放声音文件的情况下使用 android.media.audiofx.Visualizer?

python - pygame定位声音?

java - Android:在 Gridview 中使用 RadioGroup

java - 未针对特定 URL 模式调用第二个 Servlet 过滤器

android - textView.setText(string) 和 textView.text = $string 有什么区别

android - LinearLayout 扩展元素

java - 如何从非动态接收器调用 MainActivity 中带参数的函数?

java - 将字节数组转换为 Wav 文件

java - 向 Jackson Object Mapper 提供长对象池