In my meditation timer app I want to play sound which is delayed by timer. When app is in foreground it works, but it doesn't in background.
late AudioPlayer player;
@override
void initState() {
super.initState();
player = AudioPlayer();
}
Future<void> playDelayedAudio() async {
Timer(Duration(seconds: 5), () async {
await player.setAsset('sound.mp3');
await player.play();
player.stop();
});
}
I'm using just_audio package to play audio
I'm testing on iOS device, on iOS Simulator it works fine
Background modes in iOS project are enabled for "Audio, Airplay, and Picture in Picture"
There are a few platform-specific hoops to jump through for background audio, and audio_service can be useful for this. Its README offers some suggestions on how to handle timers in the background on iOS which can be employed regardless of whether you use audio_service:
Note that the
audio
background mode (on iOS) permits an app to run in the background only for the purpose of playing audio. The OS may kill your process if it sits idly without playing audio, for example, by using a timer to sleep for a few seconds. If your app needs to pause for a few seconds between audio tracks, consider playing a silent audio track to create that effect rather than using an idle timer.