Home > database >  How to loop the audio to keep playing until 3 times-Flutter
How to loop the audio to keep playing until 3 times-Flutter

Time:12-23

I am currently using audioplayers: ^0.20.1 to play and resume the video, right now I would like to loop the audio 3 times (keep looping to play the audio). As I know audioplayers package has loop property but I still don't know how to custom the loop property

CodePudding user response:

Here is how you can loop the audio player:

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: AudioPlayerLoopTesting()));
}

class AudioPlayerLoopTesting extends StatefulWidget {
  @override
  _AudioPlayerLoopTestingState createState() => _AudioPlayerLoopTestingState();
}

class _AudioPlayerLoopTestingState extends State<AudioPlayerLoopTesting> {
  AudioCache audioCache = AudioCache();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _playLoopAudio() {
    int timesPlayed = 0;
    const timestoPlay = 3;
    //audio.mp3 is the local asset file
    audioCache.play('audio.mp3').then((player) {
      player.onPlayerCompletion.listen((event) {
        timesPlayed  ;
        if (timesPlayed >= timestoPlay) {
          timesPlayed = 0;
          player.stop();
        } else {
          player.resume();
        }
      });
    });
  }

  Widget localAsset() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        const Text('Loop Local Asset'),
        ElevatedButton(
          child: const Text('Loop the audio'),
          onPressed: _playLoopAudio,
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: localAsset(),
      ),
    );
  }
}

Thumbs up if problem resolved

CodePudding user response:

to loop the audio try this :-

static AudioCache musicCache;
static AudioPlayer instance;

void playLoopedMusic() async {
musicCache = AudioCache(prefix: "audio/");
instance = await musicCache.loop("bgmusic.mp3");
// await instance.setVolume(0.5); you can even set the volume
}

void pauseMusic() {
if (instance != null) {
instance.pause(); }}

to loop it 3 time only :-

int numberOftimesToPlay=0;
playThreeTimes(){
  _audioPlayer = AudioPlayer();
        int res = await _audioPlayer.play("https://192.168.1.66/$sUrl");
        //await _audioPlayer.play("http://192.168.1.5/00001.mp3");
        if (res == 1 & numberOftimesToPlay>4) {
          numberOftimesToPlay   ;
          playThreeTimes()
          print("ok");
        } else {
          print("done");
        }}
  • Related