Reputation: 762
I am working on a meditation app where a background music starts to play when the user opens the app. App Displays list of playlist. When user click on the playlist it should play the playlist audio and pause the background music. If the music stops, background music should resume.
How can I achieve this feature using just_audio and audio_service ? I have experimented with the example_multiple_handler solution provided by the author of audio_service
package. But it didn't work.
Upvotes: 4
Views: 1514
Reputation: 822
In your case, you may not need to create two different audio handlers. Instead, you could have a single handler managing two different audio players from the just_audio package.
Here's a simple example to show you how to manage multiple audio players in an audio handler. We will create two players: backgroundMusicPlayer and playlistMusicPlayer.
Please note that the following is a simplified version, you might need to modify it according to your needs:
import 'package:audio_service/audio_service.dart';
import 'package:just_audio/just_audio.dart';
class MyAudioHandler extends BaseAudioHandler {
final _backgroundMusicPlayer = AudioPlayer();
final _playlistMusicPlayer = AudioPlayer();
MyAudioHandler() {
// init players and do something.
_init();
}
Future<void> _init() async {
// Load your music here.
try {
await _backgroundMusicPlayer.setUrl('url-of-your-background-music');
await _playlistMusicPlayer.setUrl('url-of-your-playlist-music');
} catch (e) {
// catch loading errors.
}
}
Future<void> playBackgroundMusic() async {
await _backgroundMusicPlayer.play();
}
Future<void> playPlaylistMusic() async {
await _backgroundMusicPlayer.pause();
await _playlistMusicPlayer.play();
}
Future<void> pausePlaylistMusic() async {
await _playlistMusicPlayer.pause();
await _backgroundMusicPlayer.play();
}
@override
Future<void> play() async {
// We assume that play() will play the playlist music.
await playPlaylistMusic();
}
@override
Future<void> pause() async {
// We assume that pause() will pause the playlist music.
await pausePlaylistMusic();
}
// Implement other controls such as stop(), skipToNext(), skipToPrevious() and so on...
}
Then, start the AudioService with your audio handler:
await AudioService.start(
backgroundTaskEntrypoint: _audioPlayerTaskEntrypoint,
androidNotificationChannelName: 'Audio Service Demo',
// Enable this if you want the Android service to exit the foreground state on pause.
//androidStopForegroundOnPause: true,
androidNotificationColor: 0xFF2196f3,
androidNotificationIcon: 'mipmap/ic_launcher',
androidEnableQueue: true,
);
And your _audioPlayerTaskEntrypoint function:
void _audioPlayerTaskEntrypoint() async {
AudioServiceBackground.run(() => MyAudioHandler());
}
Upvotes: 1