AudioPlayers
A Flutter plugin to play multiple simultaneously audio files, works for Android, iOS and macOS.
Install
This was orginally forked from rxlabz’s audioplayer , but the name was changed to audioplayers (mind the ‘s’); so, to add the dependency:
dependencies:
audioplayers: ^0.14.0
Discord channel
We have created a channel for audioplayers help on Fireslime’s discord, join it here
Troubleshooting
Before opening an issue, please refer to the troubleshoot guide
Usage
An AudioPlayer instance can play a single audio at a time. To create it, simply call the constructor:
AudioPlayer audioPlayer = AudioPlayer();
To use the low latency API, better for gaming sounds, use:
AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.LOW_LATENCY);
In this mode the backend won’t fire any duration or position updates.
Also, it is not possible to use the seek method to set the audio a specific position.
You can create multiple instances to play audio simultaneously.
For all methods that return a Future<int>: that’s the status of the operation. If 1, the operation was successful. Otherwise it’s the platform native error code.
Logs are disable by default! To debug, run:
AudioPlayer.logEnabled = true;
Playing Audio
There are three possible sources of audio:
Remote file on the Internet Local file on the user’s device Local asset from your Flutter project
Both for Remote Files or Local Files, use the play method, just setting appropriately the flag isLocal.
For Local Assets, you have to use the AudioCache class (see below).
To play a Remote File, just call play with the url (the isLocal parameter is false by default):
If you want to play audio for a long period of time, you need to set appropriately the flag stayAwake,
If you pass setAwake as true you need to add this permission to your app manifest:
<uses-permission android:name="android.permission.WAKE_LOCK" />.
play() async {
int result = await audioPlayer.play(url);
if (result == 1) {
// success
}
}
For a Local File, add the isLocal parameter:
playLocal() async {
int result = await audioPlayer.play(localPath, isLocal: true);
}
The isLocal flag is required only because iOS and macOS make a difference about it (Android doesn’t care either way).
There is also an optional named double volume parameter, that defaults to 1.0. It can go from 0.0 (mute) to 1.0 (max), varying linearly.
The volume can also be changed at any time using the setVolume method.
Controlling
After playing, you can control the audio with pause, stop and seek commands.
Pause will pause the audio but keep the cursor where it was. Subsequently calling play will resume from this point.
int result = await audioPlayer.pause();
Stop will stop the audio and reset the cursor. Subsequently calling play will resume from the beginning.
int result = await audioPlayer.stop();
Finally, use seek to jump through your audio:
int result = await audioPlayer.seek(Duration(milliseconds: 1200));
Also, you can resume (like play, but without new parameters):
int result = await audioPlayer.resume();
Finer Control
By default, the player will be release once the playback is finished or the stop method is called.
This is because on Android, a MediaPlayer instance can be quite resource-heavy, and keep it unreleased would cause performance issues if you play lots of different audios.
On iOS and macOS this doesn’t apply, so release does nothing.
You can change the Release Mode to determine the actual behavior of the MediaPlayer once finished/stopped. There are three options:
RELEASE: default mode, will release after stop/completed. STOP: will never release; calling play should be faster. LOOP: will never release; after completed, it will start playing again on loop.
If you are not on RELEASE mode, you should call the release method yourself; for example:
await audioPlayer.setUrl('clicking.mp3'); // prepare the player with this audio but do not start playing
await audioPlayer.setReleaseMode(ReleaseMode.STOP); // set release mode so that it never releases
// on button click
await audioPlayer.resume(); // quickly plays the sound, will not release
// on exiting screen
await audioPlayer.release(); // manually release when no longer needed
Despite the complex state diagram of Android’s MediaPlayer, an AudioPlayer instance should never have an invalid state. Even if it’s released, if resume is called, the data will be fetch again.
Stream routing
You can choose between speakers and earpiece. By default using speakers.
Toggle between speakers and earpiece.
int result = await player.earpieceOrSpeakersToggle();
⚠️ iOS stream routing not implemented
Streams
The AudioPlayer supports subscribing to events like so:
Duration Event
This event returns the duration of the file, when it’s available (it might take a while because it’s being downloaded or buffered).
player.onDurationChanged.listen((Duration d) {
print('Max duration: $d');
setState(() => duration = d);
});
Position Event
This Event updates the current position of the audio. You can use it to make a progress bar, for instance.
player.onAudioPositionChanged.listen((Duration p) => {
print('Current position: $p');
setState(() => position = p);
});
State Event
This Event returns the current player state. You can use it to show if player playing, or stopped, or paused.
player.onPlayerStateChanged.listen((AudioPlayerState s) => {
print('Current player state: $s');
setState(() => playerState = s);
});
Completion Event
This Event is called when the audio finishes playing; it’s used in the loop method, for instance.
It does not fire when you interrupt the audio with pause or stop.
player.onPlayerCompletion.listen((event) {
onComplete();
setState(() {
position = duration;
});
});
Error Event
This is called when an unexpected error is thrown in the native code.
player.onPlayerError.listen((msg) {
print('audioPlayer error : $msg');
setState(() {
playerState = PlayerState.stopped;
duration = Duration(seconds: 0);
position = Duration(seconds: 0);
});
});
AudioCache
In order to play Local Assets, you must use the AudioCache class.
Flutter does not provide an easy way to play audio on your assets, but this class helps a lot. It actually copies the asset to a temporary folder in the device, where it is then played as a Local File.
It works as a cache because it keeps track of the copied files so that you can replay them without delay.
You can find the full documentation for this class here .
playerId
By default, each time you initialize a new instance of AudioPlayer a unique playerId is generated and assigned using uuid package , this is designed this way to play multiple audio files simultaneously, if you want to play using the same instance that was created before simply pass your playerId when creating a new AudioPlayer instance.
final audioPlayer = AudioPlayer(playerId: 'my_unique_playerId');
Supported Formats
You can check a list of supported formats below:
⚠️ iOS & macOS App Transport Security
By default iOS and macOS forbid loading from non-https url. To cancel this restriction on iOS or macOS you must edit your .plist and add:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
⚠️ macOS Outgoing Connections
By default, Flutter macOS apps don’t allow outgoing connections, so playing audio files/streams from the internet won’t work. To fix this, add the following to the .entitlements files for your app:
<key>com.apple.security.network.client</key>
<true/>
Note: On Android by default, there is a restriction not allowing traffic from HTTP resources. There is a fix for this and it requires
adding android:usesCleartextTraffic="true" within your AndroidManifest.xml file located in android/app/src/main/AndroidManifest.xml.
Here is an example of how it should look like:
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
Credits
This was originally a fork of rxlabz’s audioplayer , but since we have diverged and added more features.
Thanks for @rxlabz for the amazing work!
Download Flutter AudioPlayers Source Code on GitHub
A Flutter package to play multiple audio files simultaneously (Android/iOS/web/Linux/Windows/macOS) https://github.com/bluefireteam/audioplayers 895 forks. 2,146 stars. 239 open issues. Recent commits: ci: Update super-linter to v9 (#2047)# DescriptionStacked on #2046.Update `super-linter/super-linter/slim` from v5 to v9:- `VALIDATE_KOTLIN_ANDROID` was removed, it is replaced by`VALIDATE_KOTLIN`. The ktlint code style is configured via`ktlint_code_style = intellij_idea` in `.editorconfig`, matching`ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL`.- Since v6, linter configs are loaded from `.github/linters`, so theroot `.clang-format` was ignored and the super-linter default style wasapplied. `LINTER_RULES_PATH: .` loads the configs from the repositoryroot again.- Since v8, super-linter posts a summary comment on the PR. It isdisabled, as the status checks are sufficient.super-linter v9 ships ktlint 1.8.0 and clang-format 22. To check theexisting code, `VALIDATE_ALL_CODEBASE` is temporarily set to `true` (tobe reverted before merging):- **clang-format:** passes.- **ktlint:** reports 88 violations of rules which did not exist in thektlint version of super-linter v5 (`function-expression-body`,`class-signature`, `function-signature`,`blank-line-between-when-conditions`, `enum-wrapping`,`statement-wrapping`, `kdoc`). These still need to be fixed or disabled.## Checklist- [x] The title of my PR starts with a [Conventional Commit] prefix(`fix:`, `feat:`, `refactor:`, `docs:`, `chore:`, `test:`, `ci:` etc).- [x] I have read the [Contributor Guide] and followed the processoutlined for submitting PRs.- [ ] I have updated/added tests for ALL new/updated/fixedfunctionality.- [ ] I have updated/added relevant documentation and added dartdoccomments with `///`, where necessary.- [ ] I have updated/added relevant examples in [example].## Breaking Change- [ ] Yes, this is a breaking change.- [x] No, this is *not* a breaking change.## Related Issues<!– Links –>[issue database]: https://github.com/bluefireteam/audioplayers/issues[Contributor Guide]:https://github.com/bluefireteam/audioplayers/blob/main/contributing.md#feature-requests–prs[Conventional Commit]: https://conventionalcommits.org[example]:https://github.com/bluefireteam/audioplayers/tree/main/packages/audioplayers/example , GitHub fix: Keep stopped looping players stopped (#2043)# DescriptionSplit out of #2041 so the loop handling can be reviewed separately fromthe Flutter 3.50.0 upgrade.On Flutter 3.50.0 the end-to-end tests timed out in `AudioPlayer.stop()`on macOS after looping a short sample. A looping player could restartafter it had been stopped, and the restart emitted a playing event thatoverwrote the desired state on the Dart side, so `stop()` waited for the30 second timeout.### Native- **Darwin:** `onSoundComplete` checked `isPlaying`, then awaited`seek(0)`. A `stop()` during that seek paused the player, but`onSoundComplete` resumed it afterwards anyway. It now only resumes ifthe player is still playing.- **Linux:** the end of stream message can be dispatched after a`stop()` was handled, and `OnPlaybackEnded` then called `Play()` again.It now only restarts if the player is still playing.### DartThe native fixes only prevent a restart that happens after the stopreached the native side. Events of a loop iteration that were emittedjust before can still arrive in Dart after `stop()` was called, whichcaused two hangs:- **Late completion:** the `onPlayerComplete` listener set `state =PlayerState.completed`, which also overrides the desired state. When thecomplete event of a loop iteration arrived while a stop was pending, thefollowing paused event mapped to `completed` instead of `stopped`, and`stop()` waited for the timeout. This was the iOS failure in #2041. Acompletion that arrives while a requested pause or stop is pending isnow ignored, since the request takes precedence.- **Late loop restart:** when the loop restarted right before the stop,the playing event arrived while the stop was pending and was treated astriggered by the system, which overwrote the desired `stopped` state.Playing state events that arrive while a requested state update ispending are no longer treated as triggered by the system.———Co-authored-by: Gustl22 <git@reb0.org> , GitHub ci: Start the Android emulator with SwiftShader rendering (#2059)# DescriptionSince Android Emulator 37.3.10 became the stable release (2026-11-19),the Android integration tests fail on every PR with an API 35 image,e.g. #2055, the Dependabot PRs and `fix/loop-stop`. The device loses itsnetwork and its adb connection, so `flutter test` reports `No tests werefound` (exit code 79) or `0 tests passed, 1 skipped` (exit code 1).This PR starts the emulator with `-gpu swiftshader`, which fixes itwithout pinning the emulator. It also raises the integration testemulators from API 35 to API 37.## Changes- `start-android-emulator.sh` starts the emulator with `-gpuswiftshader`.- `android` and `android-legacy` run on `android-37.0;aosp_atd` insteadof `android-35;aosp_atd`. The API 37 packages are named `android-37.0`in the SDK repository, as Google added minor SDK versions with API 36.`android-min` stays on API 24.## Findings### SymptomsOn API 35, 36 and 37, all `aosp_atd` and `default` images were affected.API 24 (`android-min`) was not.- The test server is unreachable from the device: `SocketException:Connection failed (OS Error: Network is unreachable, errno = 101),address = 10.0.2.2, port = 8080`.- Wi-Fi, the only network of these images(`androidboot.qemu.virtiowifi=1`), never becomes usable. Logcat shows: “`E WifiActiveModeWarden: Something is wrong, no client mode togglesenabledW ConnectivityService: Exception adding interface:android.os.ServiceSpecificException: Machine is not on the network (code64)E ConnectivityService: Exception in addRoute for gateway: … Machine isnot on the network (code 64)W resolv : Socket failed to connect, errno=101: Network is unreachable E android.hardware.wifi-service: Unknown iface name: wlan0 “`- In many runs adb loses the device afterwards (`adb: device offline`),while the emulator process keeps running.The runner's kernel log shows no out-of-memory kills, and the emulatordoes not crash.### CauseThe runner image does not include the emulator, so `setup-android.sh`installs the latest stable one with `sdkmanager –install "emulator"`.The system images did not change; `x86_64-35_r01.zip` was last modifiedin 2024.| Run | Date | Emulator | Android ||—|—|—|—|| `fix/loop-stop` | 2026-11-15 | 37.2.13 (build `16740729`) | passes || Dependabot, `fix/loop-stop`, #2055 | 2026-11-23 and later | 37.3.10(build `16970787`) | fails |Experiments on #2055, with the emulator output and logcat printed in thejob log, which were then removed from it:| Emulator | GPU option | API 24 | API 35 `aosp_atd` | API 35 `default`| API 36 | API 37 ||—|—|—|—|—|—|—|| 37.3.10 | none | passes | fails | fails | fails | fails || 37.2.13 (pinned) | none | passes¹ | passes | – | passes | passes || 37.3.10 | `-gpu swiftshader` | passes | – | – | passes | passes |¹ One run timed out after installing the app. This hang already happenedbefore 37.3.10 and is covered by `flutter-test-retry.sh`.Without a `-gpu` option, both versions select the same modes on a hostwithout GPU, but render differently:| Emulator | `emuglConfig_init` | Graphics Adapter ||—|—|—|| 37.2.13 | `vulkan_mode_selected:lavapipe gles_mode_selected:swangle` |`OpenGL ES Translator (Google SwiftShader)` || 37.3.10 | `vulkan_mode_selected:lavapipe gles_mode_selected:swangle` |`OpenGL ES Translator (ANGLE (Google, Vulkan 1.2.0 (SwiftShader Device(Subzero) …)))` || 37.3.10, `-gpu swiftshader` | `vulkan_mode_selected:swiftshadergles_mode_selected:swiftshader` | `OpenGL ES Translator (GoogleSwiftShader)` |37.3.10 renders OpenGL ES through ANGLE on SwiftShader's Vulkan, where37.2.13 used SwiftShader's OpenGL directly. With `-gpu swiftshader`,37.3.10 renders like 37.2.13 again, and the Wi-Fi errors no longer breakthe network. The `Unknown iface name: wlan0` lines can still appear, sothey are not the cause.Why the ANGLE renderer breaks the network is not clear. Most likely itstalls the device while the network is being set up. The release notesof 37.3.10 do not mention a rendering or networking change.### Other projectsOther projects saw the same failure from 2026-11-19 on and mostly pinnedthe emulator to 37.2.13:- mobile-dev-inc/Maestro#3769 traced it to the GPU mode. 37.3.10 rejects`-gpu swiftshader_indirect` (`Selected GPU option 'swiftshader_indirect'is not valid, switching to 'auto' mode`), and the device hangs withANGLE (`Failed to find ColorBuffer`, `invalid color buffer`). Maestronow sets `hw.gpu.mode=swiftshader`.- osociety/vernet#691, trezor/trezor-suite#35540 andpietro1704/Epub-to-Mp3#1239 pin build `16740729` through the`emulator-build` input of `ReactiveCircus/android-emulator-runner`.`ReactiveCircus/android-emulator-runner` still defaults to `-gpuswiftshader_indirect` (v2.38.0), so its users with default options arelikely affected as well. No issue has been reported there or in Google'semulator tracker yet.## Checklist- [x] The title of my PR starts with a [Conventional Commit] prefix(`fix:`, `feat:`, `refactor:`, `docs:`, `chore:`, `test:`, `ci:` etc).- [x] I have read the [Contributor Guide] and followed the processoutlined for submitting PRs.- [ ] I have updated/added tests for ALL new/updated/fixedfunctionality.- [ ] I have updated/added relevant documentation and added dartdoccomments with `///`, where necessary.- [ ] I have updated/added relevant examples in [example].## Breaking Change- [ ] Yes, this is a breaking change.- [x] No, this is *not* a breaking change.## Related IssuesUnblocks the Android jobs of #2055 and of the open Dependabot PRs.<!– Links –>[issue database]: https://github.com/bluefireteam/audioplayers/issues[Contributor Guide]:https://github.com/bluefireteam/audioplayers/blob/main/contributing.md#feature-requests–prs[Conventional Commit]: https://conventionalcommits.org[example]:https://github.com/bluefireteam/audioplayers/tree/main/packages/audioplayers/example , GitHub ci: Fix Dependabot updates failing on symlinked .gitignore (#2050)# DescriptionFollow-up to #2049: all Dependabot update jobs failed.- **Symlinked `.gitignore` files:**`packages/audioplayers_android_exo/.gitignore` and`packages/audioplayers_android_exo/android/.gitignore` were symlinks totheir `audioplayers_android` counterparts. Git refuses to followsymlinked `.gitignore` files ("Too many levels of symbolic links"),which made Dependabot's internal commits fail for the github-actions,pub and gradle ecosystems. They are now regular copies with identicalcontent.- **Remove swift ecosystem:** `Package.swift` of `audioplayers_darwin`only depends on the local, Flutter-generated `FlutterFramework` pathpackage, which doesn't exist in the repository, so the update job can'tresolve it (and there are no remote Swift dependencies to update).Tested on a fork: github-actions, pub and gradle jobs succeed and creategrouped PRs.## Checklist- [x] The title of my PR starts with a [Conventional Commit] prefix(`fix:`, `feat:`, `refactor:`, `docs:`, `chore:`, `test:`, `ci:` etc).- [x] I have read the [Contributor Guide] and followed the processoutlined for submitting PRs.- [ ] I have updated/added tests for ALL new/updated/fixedfunctionality.- [ ] I have updated/added relevant documentation and added dartdoccomments with `///`, where necessary.- [ ] I have updated/added relevant examples in [example].## Breaking Change- [ ] Yes, this is a breaking change.- [x] No, this is *not* a breaking change.## Related IssuesFollow-up to #2049.<!– Links –>[issue database]: https://github.com/bluefireteam/audioplayers/issues[Contributor Guide]:https://github.com/bluefireteam/audioplayers/blob/main/contributing.md#feature-requests–prs[Conventional Commit]: https://conventionalcommits.org[example]:https://github.com/bluefireteam/audioplayers/tree/main/packages/audioplayers/example , GitHub ci: Add Dependabot config for weekly grouped updates (#2049)# DescriptionAdds `.github/dependabot.yml` to keep dependencies up to dateautomatically.- Weekly version updates for **GitHub Actions**, **pub** (workspaceroot), **Gradle** (Android plugins + example) and **Swift PackageManager** (`audioplayers_darwin`).- Each ecosystem is bundled into a **single grouped PR** (includingmajor bumps), with `open-pull-requests-limit: 1`, so there are at most 4open Dependabot version-update PRs at a time.- Pub uses `versioning-strategy: increase` so constraints in`pubspec.yaml` are kept in sync.- Commit prefixes follow Conventional Commits (`ci:` for actions,`chore:` otherwise).## Checklist- [x] The title of my PR starts with a [Conventional Commit] prefix(`fix:`, `feat:`, `refactor:`, `docs:`, `chore:`, `test:`, `ci:` etc).- [x] I have read the [Contributor Guide] and followed the processoutlined for submitting PRs.- [ ] I have updated/added tests for ALL new/updated/fixedfunctionality.- [ ] I have updated/added relevant documentation and added dartdoccomments with `///`, where necessary.- [ ] I have updated/added relevant examples in [example].## Breaking Change- [ ] Yes, this is a breaking change.- [x] No, this is *not* a breaking change.## Related Issues<!– Links –>[issue database]: https://github.com/bluefireteam/audioplayers/issues[Contributor Guide]:https://github.com/bluefireteam/audioplayers/blob/main/contributing.md#feature-requests–prs[Conventional Commit]: https://conventionalcommits.org[example]:https://github.com/bluefireteam/audioplayers/tree/main/packages/audioplayers/example , GitHub
Provides the list of the opensource Flutter apps collection with GitHub repository.