I am building a flutter music app and using just_audio & just_audio_background packages. I want music to be played only on foreground state not in terminated state. How can I achieve this? Currently music is playing in both states.
final audio = AudioSource.uri(
Uri.parse(audioModel.url),
tag: MediaItem(
id: audioModel.id.toString(),
album: audioModel.album,
title: audioModel.title,
artUri: Uri.parse(
audioModel.image.toString(),
),
),
);
_audioPlayer.setAudioSource(audio);
_audioPlayer.play();
The official just_audio example demonstrates how to do this. i.e. From the just_audio page, click on "example", then notice that the following method is overridden in the widget:
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.paused) {
// Release the player's resources when not in use. We use "stop" so that
// if the app resumes later, it will still remember what position to
// resume from.
_player.stop();
}
}
Note that you can't directly override this method from your widget superclass, what you need to do is use the WidgetsBindingObserver
mixin with your widget. The key line of code from the example is this:
class MyAppState extends State<MyApp> with WidgetsBindingObserver {
This adds the didChangeAppLifecycleState
method which you can then override.