how to play music without pressing a button flutter

109 Views Asked by At

I was looking for a way to play music in flutter without pressing a button, but I can't find a way, does someone know how to do that

UPDATE

I've tried using initstate(), but when I implement this, the music would just stop at the middle

this is the current code I have for the initstate()

final player = AudioPlayer();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) async{
      if(!player.playing) {
        await player.setAsset("assets/mainmusic.mp3");
        await player.setLoopMode(LoopMode.all);
        await player.play();
      }
    });
  }
1

There are 1 best solutions below

2
Bishop03 On

If you are using statelesswidget, switch to a stateful widget. Then inside the State put following code.

@override
void initState(){
      'put your music play function'
      super.initState();
}