1

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);
  }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ary Anzh
  • 406
  • 3
  • 15

2 Answers2

2

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();
Ramin
  • 757
  • 1
  • 7
0

You can also use the seek method to seek the desired time and then start a timer and pause when the timer ends.

int result = await audioPlayer.seek(Duration(minutes: 5));
Timer(Duration(minutes: 3), () {
    int result = await audioPlayer.pause();
});
Mohammad Amir
  • 352
  • 2
  • 12
  • that doesn't work if the application terminated. the audio doesn't stop, can u help? – Thaiveng Mar 15 '22 at 04:46
  • @Thaiveng You can pause or stop on the player in the termination commands mentioned here https://stackoverflow.com/questions/60184497/how-to-execute-code-before-app-exit-flutter – Mohammad Amir Mar 15 '22 at 12:04