1

I would like to play a sound that will gradually accelerate playing speed, that is, 1st time it plays 1x speed, then 1.5x speed, then 2.0x speed, then 3.5x, 4x, ... something like that. I tried to write some codes, such as this:

        MediaPlayer mp;
        float mpDrumFreq = 0f;
        float frequency = 1f;

        mp = MediaPlayer.create(MainActivity.this, R.raw.tiktok);
        mp.setLooping(true);
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mpDrumFreq = Math.min(10f, (mpDrumFreq+frequency) );
                    mp.setPlaybackParams(mp.getPlaybackParams().setSpeed(mpDrumFreq));
                }
            }
        });

        TextView play = findViewById(R.id.play);

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.start();
            }
        });

Here, the MediaPlayer mp plays sound. I am trying to increasing speed inside setOnCompletionListener with this line mp.setPlaybackParams(mp.getPlaybackParams().setSpeed(newSpeed)); And I some other variations of it. But it did not work. I don't know why. Does anyone know how to do this?

In this case I tried with MediaPlayer but feel free to suggest anything such as SoundPool or some other library. Can anyone help me?

Qazi Fahim Farhan
  • 2,066
  • 1
  • 14
  • 26

1 Answers1

1

You can try with a SoundPool:

private static SoundPool sound;
private static SparseIntArray soundPoolMap = new SparseIntArray();
...
// 1 - use one thread
sound = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
soundPoolMap.put(0, sound.load(application, R.raw.sound, 0));
...
// last parameter - rate of sound
sound.play(soundPoolMap.get(0), 1.0f, 1.0f, 0, 0, 1f);

But as it is written Howard Liu here SoundPool doesn't have setOnCompletionListener() and suggests using custom class.

alexrnov
  • 2,346
  • 3
  • 18
  • 34