When I built Sleep Sounds: Brown Noise, Fan, the brief sounded simple: play brown noise, fan sounds, white noise, rain and ocean waves from the phone on the nightstand, all night long. In practice it meant solving three problems every sleep app shares: sounds must keep playing with the screen off, several sounds must mix at once, and the audio must stop gently instead of cutting out mid-dream. The finished app layers up to 10 sounds with individual volumes, fades the mix out with a sleep timer, pauses for phone calls, and works offline from the first launch with 6 sounds built in. You can see the finished app in the Sleep Sounds case study.
This guide shows how to build the same feature in your own Flutter app: play and loop sounds with just_audio, mix them, keep them alive in the background, and build a sleep timer that fades the volume out instead of stopping abruptly.
What is background audio in Flutter?
Background audio in Flutter is audio that keeps playing after the user locks the phone or switches to another app. A plain AudioPlayer stops when the operating system suspends the app, because the system treats a backgrounded app as idle work it is free to kill. Background audio works only when the app tells the system, in advance, that it is a media player: on Android that means running playback inside a foreground service with a persistent notification, and on iOS it means enabling the Audio background mode and configuring an audio session. The just_audio package handles playback itself, the just_audio_background package adds the Android foreground service, and the audio_session package configures how the app interacts with phone calls, alarms and other apps.
Which packages do I need for a sleep sounds app?
Add all three to pubspec.yaml and run flutter pub get. The table below shows what each package does and what breaks if you skip it.
| Package | Job | What breaks without it |
|---|---|---|
| just_audio | Play, loop and mix audio files | No playback at all |
| audio_session | Configure the audio session, handle interruptions | Audio stops on a call and never resumes; other apps keep playing over yours |
| just_audio_background | Foreground service and lock-screen controls on Android | Audio stops minutes after the screen turns off |
Do not use the older audioplayers package for this job: it is fine for short sound effects, but just_audio gives you gapless looping, per-player volume and the background integration a sleep app depends on. If you have not worked with audio assets before, the offline audio guide covers caching and playing MP3 files on-device.
How do I play and loop a single sound?
Playing and looping one sound takes four calls on an AudioPlayer: setAsset loads the file, setLoopMode with LoopMode.one repeats it forever, setVolume sets the level, and play starts it. LoopMode.one is the right choice for rain, fan noise and ocean waves, because a sleep sound must never reach the end of the file and go silent. Keep the player in a service class rather than a widget, so the UI can rebuild without touching playback.
final player = AudioPlayer();
Future<void> playRain() async {
await player.setAsset('assets/sounds/rain.mp3');
await player.setLoopMode(LoopMode.one);
await player.setVolume(0.7);
await player.play();
}
Future<void> stopRain() async {
await player.stop();
}
Always await setAsset before calling play: starting playback before the file is loaded throws a PlayerException. Dispose the player with dispose when the feature is done, and never create a new AudioPlayer every time the user taps a sound — reuse one player per sound slot, as the mixer below does.
How do I mix several sounds at once?
Mixing sounds in Flutter means running one AudioPlayer per sound and starting them together. Each player has its own volume, so a rain slider and a fan slider are just two calls to setVolume on two different players. Sleep Sounds layers up to 10 sounds this way, each with its own volume, and the mix is saved so the user can replay it with one tap. Ten players is the practical ceiling: each player holds its own decoder and buffer, and more than that wastes memory on low-end phones. Keep the mixer in a single class that owns the map of players, and expose only addSound, setVolume, playAll and dispose to the UI.
class SoundMixer {
final Map<String, AudioPlayer> _players = {};
Future<void> addSound(String id, String asset) async {
final player = AudioPlayer();
await player.setAsset(asset);
await player.setLoopMode(LoopMode.one);
_players[id] = player;
}
Future<void> setVolume(String id, double volume) async {
await _players[id]?.setVolume(volume.clamp(0.0, 1.0));
}
Future<void> playAll() async {
for (final player in _players.values) {
await player.play();
}
}
Future<void> dispose() async {
for (final player in _players.values) {
await player.dispose();
}
_players.clear();
}
}
Start every player in the same frame so the sounds begin together. Save each mix as a list of sound ids and volumes in local storage, and loading a mix is just a loop that calls addSound and setVolume for each entry. Ready-made mixes such as Deep Sleep or Storm Shelter are the same data structure with preset values.
How do I keep audio playing with the screen off?
Audio keeps playing with the screen off only when playback runs in a foreground service on Android and the app declares the Audio background mode on iOS. The just_audio_background package does the Android half: call JustAudioBackground.init once in main before runApp, with a notification channel id and name, and every AudioPlayer you create afterwards runs inside the service. The service shows a persistent notification with play and pause controls, which is also how the user stops the audio from the lock screen. On iOS, open the Runner target in Xcode, go to Signing and Capabilities, add Background Modes, and tick Audio, AirPlay, and Picture in Picture. Without that tick, iOS suspends the app a few seconds after the screen locks and the sound stops.
Future<void> main() async {
await JustAudioBackground.init(
androidNotificationChannelId: 'com.example.sleep.sounds',
androidNotificationChannelName: 'Sleep sounds',
androidNotificationOngoing: true,
);
runApp(const SleepSoundsApp());
}
Set androidNotificationOngoing to true so the user cannot swipe the notification away while audio is playing. Test this on a real device, not an emulator: emulators often keep backgrounded apps alive longer than real phones do. If playback still stops, ask the user to disable battery optimization for the app, and check that the notification is visible while the audio plays — if there is no notification, the foreground service is not running.
How do I build a sleep timer with a fade-out?
A sleep timer with a fade-out is a Timer.periodic that lowers the master volume during the last minute instead of stopping the audio at once. An abrupt stop wakes light sleepers, while a 60-second fade lets the brain tune the sound out gradually. Sleep Sounds offers timers from 15 minutes to 8 hours or a set clock time, and the fade always covers the final minute. The timer below ticks every 5 seconds, computes how much time is left, and scales the volume from its starting level down to zero across the fade window. If the user changes the duration, cancel the old timer and start a new one from the remaining time so the fade restarts cleanly.
Timer? _sleepTimer;
void startSleepTimer(Duration duration, AudioPlayer player) {
_sleepTimer?.cancel();
const fade = Duration(seconds: 60);
final fadeStart = duration > fade ? duration - fade : Duration.zero;
const startVolume = 0.8;
_sleepTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
final elapsed = Duration(seconds: 5 * timer.tick);
if (elapsed >= fadeStart) {
final remaining = duration - elapsed;
final fraction =
(remaining.inMilliseconds / fade.inMilliseconds).clamp(0.0, 1.0);
player.setVolume(startVolume * fraction);
}
if (elapsed >= duration) {
timer.cancel();
player.stop();
}
});
}
Show the remaining time on the lock screen and in the app, and update it from the same timer so the display never disagrees with the audio. When the timer fires, stop the players and cancel the foreground service notification so the phone goes quiet.
How do I handle phone calls and other interruptions?
Phone calls and other interruptions are handled through the audio_session package, which reports them as a stream of events. Configure the session once with AudioSessionConfiguration.music, activate it, and listen to interruptionEventStream: when an interruption begins, pause the players or lower the volume for a duck event; when it ends, resume playback. Sleep Sounds pauses for phone calls, which is the behavior users expect at 3 a.m. — a sleep sound must never talk over a call. The duck event is different from a pause: navigation prompts and voice assistants duck the volume temporarily, so lower it to 0.2 and restore it when the event ends instead of stopping.
Future<void> configureAudioSession(AudioPlayer player) async {
final session = await AudioSession.instance;
await session.configure(AudioSessionConfiguration.music());
await session.setActive(true);
session.interruptionEventStream.listen((event) {
if (event.begin) {
switch (event.type) {
case AudioInterruptionType.duck:
player.setVolume(0.2);
case AudioInterruptionType.pause:
case AudioInterruptionType.unknown:
player.pause();
}
} else {
player.play();
}
});
}
Do not resume automatically after every interruption: if the user paused the audio themselves before the call, resuming would surprise them. Track whether the app was playing when the interruption began, and resume only in that case.
How do I make sounds work offline?
Sounds work offline when the files live on the device instead of streaming from a server. Bundle the most popular sounds as assets so they play from the first launch with no download, and download the rest once into the application documents directory. Sleep Sounds ships 6 sounds offline from the first launch and the other 23 download once, which keeps the install small while covering the full library. Check whether the file already exists before downloading, and play from the local file with setFilePath instead of setAsset. Show a download progress indicator per sound, and never block the play button on a download the user did not ask for.
Future<File> localSoundFile(String name) async {
final dir = await getApplicationDocumentsDirectory();
return File(dir.path + '/sounds/' + name);
}
Future<void> playDownloadedSound(AudioPlayer player, String name) async {
final file = await localSoundFile(name);
if (await file.exists()) {
await player.setFilePath(file.path);
await player.setLoopMode(LoopMode.one);
await player.play();
}
}
Keep the download list small and the files compressed: a 10-minute rain loop at 128 kbps is about 10 MB, so 23 sounds is a large download if the user fetches them all at once. Download on Wi-Fi only by default, and let the user delete downloaded sounds to free space.
Testing checklist before you ship
Test a sleep sounds app the way a tired user will use it, not the way a developer tests it. Start a mix, lock the phone, and confirm the audio is still playing after 30 minutes on a real Android device and a real iPhone. Make a phone call during playback and confirm the audio pauses and resumes. Set a 15-minute timer and confirm the fade-out is smooth and the audio stops at zero. Switch the phone to airplane mode and confirm the bundled sounds still play. Finally, leave the app playing overnight on your own nightstand: if it is still playing in the morning without draining the battery or showing a crash, it is ready. A breathing exercise or a pomodoro timer pairs well with the same background-audio stack, so the work here pays off across the app.
Build the mixer first, then the background service, then the timer and the interruption handling — in that order, because each layer is easy to test on its own and painful to debug together. When the whole chain works, you have a sleep sounds app that plays all night, fades out gently, and never wakes the user up by accident.
Get in touch and let's talk about your project.
Originally published at uzairxdev.online
Top comments (0)