simple_audio_kit 1.0.0
simple_audio_kit: ^1.0.0 copied to clipboard
A professional, zero-config audio playback library for Flutter. Supports playlists, background playback, lock screen controls, and robust error handling out-of-the-box.
simple_audio #
Simplified audio playback for Flutter. simple_audio 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 caching 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.
Installation #
Add the package to your pubspec.yaml:
dependencies:
simple_audio:
path: ../simple_audio # Or substitute with your package source
Then run:
flutter pub get
Quick Start #
import 'package:flutter/material.dart';
import 'package:simple_audio/audio.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.
Navigation & Queuing #
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, orall).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.5for podcasts).Audio.setVolume(double volume): Adjusts internal player volume (between0.0and1.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 currentDuration(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/audio.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_SERVICEandFOREGROUND_SERVICE_MEDIA_PLAYBACKpermissions insideandroid/app/src/main/AndroidManifest.xml. You must also define the receiver in your manifest. (See theaudio_servicedocumentation for exact setup details). - iOS: Open Xcode and verify that the
UIBackgroundModesarray in yourInfo.plistfile contains theaudioflag.
Cleartext HTTP traffic not permitted #
To support on-the-fly streaming caching gracefully, simple_audio uses LockCachingAudioSource. This creates a local loopback server (127.0.0.1) under the hood to stream cached chunks.
Because of this, you must enable cleartext traffic in Android, otherwise caching will crash your player stream.
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. Thankfully, simple_audio uses LockCachingAudioSource automatically for all HTTP(S) links, meaning the track will aggressively cache to the device as it streams. Ensure your test devices have sufficient free disk space to store audio data dynamically.