simple_audio_kit

Simplified audio playback for Flutter. simple_audio_kit provides a clean, generic API over proven plugins (just_audio, audio_session, and audio_service) for music, podcasts, audiobooks, local files, assets, radio streams, and sound effects.

Overview

We handle the heavy lifting behind the scenes so that you can focus on building your app.

  • Generic Audio Support: Handles network streams, local files, bundled Flutter assets, Android content URIs, and protected streams with custom HTTP headers.
  • Offline Caching: Seamlessly cache network audio to local disk for instant offline playback and reduced network bandwidth.
  • Versatile Audio Metadata: Supports titles, artists, album names, genres, artwork URLs, track duration, custom IDs, and arbitrary extras data.
  • Configurable Audio Sessions: Tune device session behavior for music, speech/podcasts, or ambient sound effects using AudioSessionConfiguration.
  • Multi-Player Support: Use the global Audio facade or instantiate SimpleAudioController for independent concurrent players (e.g. playing background music + sound effects).
  • Minimal Integration: Playback state works from Dart; Android and iOS need the native background-audio setup shown below for system media controls.
  • Audio Focus: Handles system interruptions (phone calls, navigation prompts) safely with automatic ducking and pausing.

Add the package to your pubspec.yaml:

dependencies:
  simple_audio_kit: ^1.2.0

Then run:

flutter pub get

Platform support

Platform Playback Lock screen / notification controls Offline Caching
Android Yes Yes — host setup required Yes
iOS Yes Yes — host setup required Yes
macOS Yes Yes Yes
Web Yes Browser-dependent Media Session support No package disk cache
Windows Yes No — runs headless Yes
Linux Yes No — runs headless Yes

Disk caching uses the configured cache directory (the system temporary directory by default), so the operating system may evict files. Supply AudioCacheManager(customCacheDir: ...) when your app needs a specific persistent location.

Background audio setup

Background playback and system media controls require the host configuration from audio_service. The included example contains a working baseline:

  • Android: add the internet, wake-lock, and foreground-service permissions, register AudioService and MediaButtonReceiver, and make MainActivity extend AudioServiceActivity. See example/android/app/src/main/AndroidManifest.xml.
  • iOS: add audio to UIBackgroundModes. See example/ios/Runner/Info.plist.
  • macOS: sandboxed apps that stream network audio need the com.apple.security.network.client entitlement.

If system-media initialization fails, playback continues in headless mode and an initFailed event is reported on Audio.errorStream.

Quick Start

import 'package:flutter/material.dart';
import 'package:simple_audio_kit/simple_audio_kit.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize early. Calling init again updates session/cache settings.
  await Audio.init();
  
  runApp(const MyApp());
}

// 2. Play any audio anywhere!
Future<void> playAudio() async {
  await Audio.play(
    'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
    title: 'Song Title',
    artist: 'Artist Name',
    album: 'Album Name',
    cache: true, // Enables automatic offline disk caching!
  );
}

Generic Audio Sources & Constructors

AudioItem offers named constructors for different audio types:

// Network stream with disk caching enabled
final networkItem = AudioItem.network(
  'https://api.example.com/stream.mp3',
  title: 'Podcast Episode 1',
  artist: 'Host Name',
  cache: true, // Automatically saved to disk during playback
  headers: {'Authorization': 'Bearer token'},
  extras: {'episodeId': 101, 'chapter': 3},
);

// Local file audio
final fileItem = AudioItem.file(
  '/storage/emulated/0/Download/audio.mp3',
  title: 'Downloaded Track',
);

// Bundled Flutter asset
final assetItem = AudioItem.asset(
  'assets/sounds/beep.mp3',
  title: 'Notification Sound',
);

Offline Caching & Cache Management

simple_audio_kit includes built-in offline caching powered by AudioCacheManager.

Enabling Caching

You can enable caching per track or globally:

// 1. Enable per track
Audio.play('https://example.com/audio.mp3', cache: true);

// 2. Enable globally for all network tracks
await Audio.init(defaultCache: true);

Managing the Cache & Preloading Tracks

Pre-download tracks in the background so they play instantly offline:

// Preload a track before the user hits play
await Audio.preload(networkItem);

// Check if a URL is already cached
final isCached = await Audio.isCached('https://example.com/audio.mp3');

// Get total disk space used by cached audio (in bytes)
final bytes = await Audio.getCacheSize();

// Delete specific cached item or clear the entire cache
await Audio.removeCached('https://example.com/audio.mp3');
await Audio.clearCache();

Configurable Audio Session Categories

Configure the system audio session for music, speech (podcasts/audiobooks), or ambient sound effects during Audio.init():

// For Podcasts / Audiobooks (speech focus)
await Audio.init(
  sessionConfiguration: const AudioSessionConfiguration.speech(),
);

// For Games or Ambient Apps
await Audio.init(
  sessionConfiguration: const AudioSessionConfiguration.ambient(),
);

Calling Audio.init again reapplies the session configuration to the running engine.

Multiple Audio Players

For apps that need multiple independent players (e.g., playing background music while playing sound effects or comparing two audio tracks), instantiate SimpleAudioController directly:

final sfxPlayer = SimpleAudioController(
  sessionConfiguration: const AudioSessionConfiguration.ambient(),
);

await sfxPlayer.init();
await sfxPlayer.play('asset:///assets/sfx/explosion.mp3');
// Dispose standalone controllers when their owner is removed.
await sfxPlayer.dispose();

Only the global Audio facade owns lock-screen and notification controls. Standalone controllers intentionally run headless.

Full API Reference

The Audio facade provides static access to all audio playback actions.

Core Playback

  • Audio.init({AudioSessionConfiguration? sessionConfiguration, bool? defaultCache, AudioCacheManager? cacheManager}): Prepares or reconfigures the audio engine.
  • Audio.play(...): Plays an audio track immediately with optional metadata, artwork, headers, extras, and cache: true.
  • Audio.playList(List<AudioItem> items): Replaces the queue and starts its first valid item. An empty or wholly invalid list stops playback.
  • Audio.pause(): Pauses the currently playing track.
  • Audio.resume(): Resumes the paused track.
  • Audio.stop(): Stops the audio session and closes background notifications.
  • Audio.next() / Audio.previous(): Navigates the current queue.
  • Audio.seek(Duration position): Seeks within the current item.
  • Audio.setSpeed(double speed): Changes playback speed.
  • Audio.setVolume(double volume): Sets volume from 0.0 to 1.0.
  • Audio.setRepeatMode(AudioRepeatMode mode): Selects off, one, or all.
  • Audio.setShuffle(bool enable): Enables or disables queue shuffling.
  • Audio.dispose(): Releases the engine.

Cache Control

  • Audio.preload(AudioItem item): Pre-downloads a track into the disk cache.
  • Audio.preloadUrl(String url, {Map<String, String>? headers}): Pre-downloads a URL directly.
  • Audio.isCached(String url): Checks if a track is cached locally.
  • Audio.getCacheSize(): Returns cache size in bytes.
  • Audio.clearCache(): Clears all cached audio files.
  • Audio.removeCached(String url): Removes a specific track from disk cache.
  • Audio.cacheManager: Direct access to the AudioCacheManager instance.

Supported Schemes

Scheme Example
https / http https://example.com/track.mp3
file file:///storage/emulated/0/track.mp3
asset asset:///assets/beep.mp3 (or shorthand asset:assets/beep.mp3)
content content://media/external/audio/media/42 (Android pickers)

State Streams & Event Hooks

  • Audio.playbackStateStream: Stream of state (playing, paused, stopped).
  • Audio.playbackStateNow: Current playback state snapshot.
  • Audio.positionStream: Position Duration stream.
  • Audio.bufferedPositionStream: Buffered position stream.
  • Audio.isBufferingStream: Whether network data is buffering.
  • Audio.durationStream: Total track length stream.
  • Audio.speedStream / Audio.volumeStream: Current tuning values.
  • Audio.currentItemStream: Active AudioItem stream.
  • Audio.currentItemNow: Active item snapshot.
  • Audio.queue: Unmodifiable list of accepted queue items.
  • Audio.repeatModeStream / Audio.shuffleStream: Queue mode streams.
  • Audio.errorStream: Stream of SimpleAudioExceptions.
  • Audio.onPlay, Audio.onPause, Audio.onComplete: Event callbacks.

Libraries

simple_audio_kit
Simple Audio — a simplified audio playback API for Flutter.