Reputation: 5932
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?
Upvotes: 2
Views: 4090
Reputation: 3142
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());
}
Upvotes: 8
Reputation: 54
Maybe audio_service would suit your needs. From its description, it should actually be exactly what you are searching for.
This plugin wraps around your existing audio code to allow it to run in the background, and it provides callbacks to allow your app to respond to the media buttons on your headset, Android lock screen and notification, iOS control center, wearables and Android Auto.
Upvotes: 0