Search code examples
flutterdartaudiojust-audio

How to play and stop audio at specific time?


I have an audio player app using just_audio plugin. How to play and stop audio at a specific time?

For example, I have an audio file that is 20 minutes long. I want when I press play button, the audio will run at the 5th minute and stop at the 8th minute.

Here is my code:

void _setInitialPlaylist() async {
    final myAudio1 = Uri.parse("asset:///audio/myAudio.mp3"); // I want this audio play at 00.05.00, stop at 00.08.00
    final myAudio2 = Uri.parse("asset:///audio/myAudio.mp3"); // I want this audio play at 00.09.00, stop at 00.12.00
    final myAudio3 = Uri.parse("asset:///audio/myAudio.mp3"); // I want this audio play at 00.15.00, stop at 00.19.00
    _playlist = ConcatenatingAudioSource(children: [
      AudioSource.uri(myAudio1, tag: 'myAudio1'),
      AudioSource.uri(myAudio2, tag: 'myAudio2'),
      AudioSource.uri(myAudio3, tag: 'myAudio3'),
    ]);
    await _audioPlayer.setAudioSource(_playlist);
  }

Solution

  • From the documentation:

    await player.setClip(start: Duration(seconds: 10), end: Duration(seconds: 20));
    await player.play(); // Waits until the clip has finished playing
    

    In your case it becomes:

    await player.setClip(start: Duration(minutes: 5), end: Duration(minutes: 8));
    await player.play();