1

I want to play a soundtrack where I need full control over the playback speed. I have tried several ways to do this in android studio, but I'm facing the following problems:

  • my API level is 19, so I cannot use MediaPlayer to change the speed
  • SoundPool is supposed to play short sounds and stops after a few seconds of music

What else could I try?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
wave
  • 178
  • 2
  • 8
  • 1
    `my API level is 19, so I cannot use MediaPlayer` MediaPlayer has been added in API Level **1**. – Phantômaxx Mar 20 '17 at 12:27
  • 1
    MediaPlayer's functionality for setting the playback speed was introduced in API 23; of course I can use MediaPlayer, but not to change the speed. – wave Mar 20 '17 at 12:33
  • Just to answer the question properly: I used an AudioTrack with setPlaybackRate(), this seems to be the most reasonable solution for my api. – wave Mar 30 '17 at 16:06
  • Does it answer your question? If so, please provide your own answer and accept it (in a couple of days you'll be able to). – Phantômaxx Mar 30 '17 at 16:07

1 Answers1

1

Something like this:

public class AudioActivity extends Activity {
AudioTrack audio = new AudioTrack(AudioManager.STREAM_MUSIC,
        44100,
        AudioFormat.CHANNEL_OUT_STEREO,
        AudioFormat.ENCODING_PCM_16BIT,
        intSize, //size of pcm file to read in bytes
        AudioTrack.MODE_STATIC);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //read track from file
        File file = new File(getFilesDir(), fileName);

        int size = (int) file.length();
        byte[] data = new byte[size];

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.read(data, 0, size);
            fileInputStream.close();

            audio.write(data, 0, data.length);
        } catch (IOException e) {}
    }

    //change playback speed by factor
    void changeSpeed(double factor) {
        audio.setPlaybackRate((int) (audio.getPlaybackRate() * factor));
    }
}
wave
  • 178
  • 2
  • 8