Home > Back-end >  Flutter how to play and stop audio at specific time?
Flutter how to play and stop audio at specific time?

Time:01-07

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);
  }

CodePudding user response:

You can 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();
});

CodePudding user response:

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();
  •  Tags:  
  • Related