Flutter how to play and stop audio at specific time?

1,497

Solution 1

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

Solution 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();
Share:
1,497
Ary Anzh
Author by

Ary Anzh

Updated on January 03, 2023

Comments

  • Ary Anzh
    Ary Anzh over 1 year

    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);
      }
    
  • Thaiveng
    Thaiveng about 2 years
    that doesn't work if the application terminated. the audio doesn't stop, can u help?
  • Mohammad Amir
    Mohammad Amir about 2 years
    @Thaiveng You can pause or stop on the player in the termination commands mentioned here stackoverflow.com/questions/60184497/…