Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Music plays after closing application

I want to make a music player by flutter. I want to, when user play a music and close the application, The music is playing in the background as a service.

I googled and i found out,with these flutter libraries, not possible to do (means music player work as a background service) ? Is it true?

Or is there any way to do that?

like image 885
Cyrus the Great Avatar asked Jan 18 '26 21:01

Cyrus the Great


1 Answers

To stop the music when the app is in the background, you need to bind the Audio Player to the WidgetsBindingObserver to listen to the app lifecycle state changes.

create a custom class for example

 class _Handler extends WidgetsBindingObserver {
    @override
    void didChangeAppLifecycleState(AppLifecycleState state) {
      if (state == AppLifecycleState.resumed) {
         AudioPlayer.resume(); // Audio player is a custom class with resume and pause static methods
       } else {
         AudioPlayer.pause();
       }
     }
  }

and then inside your main.dart you can you use it as bellow:

main() async {
   WidgetsFlutterBinding.ensureInitialized();

   runApp(YourApp());

    WidgetsBinding.instance.addObserver(new _Handler());
  }
like image 111
Seddiq Sorush Avatar answered Jan 21 '26 08:01

Seddiq Sorush