simple_audio_kit

Simplified audio playback for Flutter. simple_audio_kit provides a clean, opinionated API over proven plugins (just_audio and audio_service), allowing you to add professional audio playback to your app in seconds without writing tedious configurations.

Overview

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

  • Zero Configuration: Background play, locking screens, and state management work automatically out-of-the-box.
  • Advanced Features: Supports repeat modes, shuffling, track preloading, and robust error recovery.
  • Audio Focus: Handles system interruptions (like a phone call or navigation prompt) safely with automatic ducking and pausing.
  • Clean API: Provides easy-to-use static methods and streams.

Add the package to your pubspec.yaml:

dependencies:
  simple_audio_kit: ^1.0.0

Then run:

flutter pub get

Quick Start

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 1. Initialize the audio service once
  await Audio.init();
  
  runApp(const MyApp());
}

// 2. Play any URL anywhere in your app!
void playMusic() {
  Audio.play('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3');
}

Full API Reference

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

Core Playback

  • Audio.init(): Prepares the audio engine. Call this once early in your app lifecycle.
  • Audio.play(String url, {String? title, String? artist, String? image}): Plays an audio track immediately. Providing metadata auto-syncs with the phone's lock screen.
  • Audio.playList(List<AudioItem> items): Clears the queue and loads the provided playlist.
  • 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(): Skips to the next track in the playlist.
  • Audio.previous(): Skips to the previous track.
  • Audio.setRepeatMode(AudioRepeatMode mode): Sets looping behavior (off, one, or all).
  • Audio.setShuffle(bool enable): Shuffles the active playlist dynamically.

Advanced Controls

  • Audio.seek(Duration position): Jumps to a specific timestamp in the current track.
  • Audio.setSpeed(double speed): Changes the playback speed multiplier (e.g. 1.5 for podcasts).
  • Audio.setVolume(double volume): Adjusts internal player volume (between 0.0 and 1.0).

State Streams (For UI)

Everything you need to build reactive audio players.

  • Audio.playbackStateStream: Stream of the current state (playing, paused, stopped).
  • Audio.positionStream: Stream of the track's current Duration (perfect for progress bars).
  • Audio.durationStream: Stream reflecting the total length of the current track.
  • Audio.repeatModeStream: Listen to repeat mode changes.
  • Audio.shuffleStream: Listen to shuffle state changes.
  • Audio.speedStream: React to playback reading speed changes.
  • Audio.volumeStream: React to internal volume ratio changes.

Event Hooks

Fire custom code during player phase changes:

  • Audio.onPlay: Fires when a track starts or resumes.
  • Audio.onPause: Fires when a track pauses mid-item.
  • Audio.onComplete: Fires when the final track of your queue finishes.

Examples

Creating a Reactive Play/Pause Button

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

class PlayPauseButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<AudioPlaybackState>(
      stream: Audio.playbackStateStream,
      initialData: Audio.playbackStateNow,
      builder: (context, snapshot) {
        // Evaluate our state stream safely
        final isPlaying = snapshot.data == AudioPlaybackState.playing;
        
        return IconButton(
          icon: Icon(isPlaying ? Icons.pause : Icons.play_arrow),
          iconSize: 64,
          onPressed: () {
            if (isPlaying) {
              Audio.pause(); // Pause if playing
            } else {
              Audio.resume(); // Resume if paused/stopped
            }
          },
        );
      },
    );
  }
}

Loading and Shuffling a Playlist

Future<void> loadAlbum() async {
  await Audio.playList([
    AudioItem(url: 'https://example.com/track1.mp3', title: 'Track 1'),
    AudioItem(url: 'https://example.com/track2.mp3', title: 'Track 2'),
    AudioItem(url: 'https://example.com/track3.mp3', title: 'Track 3'),
  ]);
  
  // Turn on repeating for the whole playlist
  await Audio.setRepeatMode(AudioRepeatMode.all);
  
  // Shuffle the playlist
  await Audio.setShuffle(true);
}

Troubleshooting

Lock Screen / Background Playback Isn't Working

Behind the scenes, we use audio_service. Background playback requires native OS permissions:

  • Android: Ensure you've declared the FOREGROUND_SERVICE and FOREGROUND_SERVICE_MEDIA_PLAYBACK permissions inside android/app/src/main/AndroidManifest.xml. You must also define the receiver in your manifest. (See the audio_service documentation for exact setup details).
  • iOS: Open Xcode and verify that the UIBackgroundModes array in your Info.plist file contains the audio flag.

Cleartext HTTP traffic not permitted

Backend streaming often requires permission to handle local loopback or HTTP links. For the best stability across Android devices, we recommend enabling cleartext traffic.

Add android:usesCleartextTraffic="true" to your <application> tag in AndroidManifest.xml:

<application
    android:name="${applicationName}"
    android:usesCleartextTraffic="true"
    android:icon="@mipmap/ic_launcher">

"AudioSession configuration failed" logs

If you notice that AudioSession initialization sometimes fails in hot-reloads, it's safe to ignore. simple_audio catches the failure gracefully and recovers smoothly under the hood.

The stream buffers constantly

Streaming large tracks on poor networks can cause stuttering. simple_audio_kit uses native buffering strategies to keep playback smooth. Ensure your test devices have a stable internet connection for high-quality audio streaming.

Libraries

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