audioplayers
audioplayers copied to clipboard
AndroidAudioError java.lang.IllegalStateException during setSource
Checklist
- [X] I read the troubleshooting guide before raising this issue
- [X] I made sure that the issue I am raising doesn't already exist
Current bug behaviour
I'm writing a function that will keep playing audio file on loop. This is what it looked like from my method.
final Map<String, String> voiceMap = {
"1": "sound/one.mp3",
"2": "sound/two.mp3",
"3": "sound/three.mp3",
"4": "sound/four.mp3",
};
await AudioPlayer.global
.setAudioContext(AudioContextConfig(/*...*/).build());
final player = AudioPlayer();
await player.play(
AssetSource(
voiceMap[number.toString()]!,
),
);
final start = player.onPlayerComplete.listen((_) async {
final pref = await SharedPreferences.getInstance();
final status = pref.getBool(currentPage);
for (var i = 1; i <= 15; i++) {
if (status != null) {
break;
}
player.play(
AssetSource(
voiceMap[number.toString()]!,
),
);
}
});
This error will not happen if i untick 'Uncaught Exception' in VSCode which obviously is undesired. And the app still crash regardless after a few loops.
Expected behaviour
The player played a sound on loop without issues.
Steps to reproduce
- flutter create
- add .mp3 assets and audioplayers 5.2.1 inside pubspec.yaml.
- copy the sample.
- Execute
flutter runon the code sample.
Code sample
Code sample
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Future<void> _incrementCounter() async {
await AudioPlayer.global
.setAudioContext(AudioContextConfig(/*...*/).build());
final player = AudioPlayer();
await player.play(AssetSource(
'sound/one.mp3',
));
player.onPlayerComplete.listen((_) async {
for (var i = 1; i <= 15; i++) {
player.play(
AssetSource(
'sound/one.mp3',
),
);
}
});
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
pubspec.yaml
name: bug_audio
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1
environment:
sdk: '>=3.1.5 <4.0.0'
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
audioplayers: ^5.2.1
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^2.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/sound/one.mp3
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
Affected platforms
Android
Platform details
OPPO Reno 5 Pro 256GB, Using ColorOS 13 (Android 13) API Level 33.
AudioPlayers Version
5.2.1
Build mode
debug
Audio Files/URLs/Sources
https://voca.ro/1fURFPHbF0zJ
Screenshots
No response
Logs
AndroidAudioError java.lang.IllegalStateException during setSourceUrl
Full Logs
Debugger Log
PlatformException (PlatformException(AndroidAudioError, null, java.lang.IllegalStateException
at android.media.MediaPlayer._setDataSource(Native Method)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1286)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1267)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1224)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1189)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1154)
at xyz.luan.audioplayers.source.UrlSource.setForMediaPlayer(UrlSource.kt:16)
at xyz.luan.audioplayers.player.MediaPlayerPlayer.setSource(MediaPlayerPlayer.kt:55)
at xyz.luan.audioplayers.player.WrappedPlayer.setSource(WrappedPlayer.kt:32)
at xyz.luan.audioplayers.AudioplayersPlugin.methodHandler(AudioplayersPlugin.kt:127)
at xyz.luan.audioplayers.AudioplayersPlugin.access$methodHandler(AudioplayersPlugin.kt:29)
at xyz.luan.audioplayers.AudioplayersPlugin$onAttachedToEngine$1$1.invoke(AudioplayersPlugin.kt:50)
at xyz.luan.audioplayers.AudioplayersPlugin$onAttachedToEngine$1$1.invoke(AudioplayersPlugin.kt:50)
at xyz.luan.audioplayers.AudioplayersPlugin$safeCall$1.invokeSuspend(AudioplayersPlugin.kt:75)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
, null))
Console Log
/flutter ( 6916): AudioPlayers Exception: AudioPlayerException(
I/flutter ( 6916): AssetSource(path: sound/four.mp3),
I/flutter ( 6916): PlatformException(AndroidAudioError, MEDIA_ERROR_UNKNOWN {what:-38}, MEDIA_ERROR_UNKNOWN {extra:0}, null)
E/flutter ( 6916): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(AndroidAudioError, MEDIA_ERROR_UNKNOWN {what:-38}, MEDIA_ERROR_UNKNOWN {extra:0}, null)
E/flutter ( 6916):
Flutter doctor:
[√] Flutter (Channel stable, 3.13.9, on Microsoft Windows [Version
10.0.22621.2428], locale th-TH)
• Flutter version 3.13.9 on channel stable at D:\flutter\src\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision d211f42860 (3 weeks ago), 2023-10-25 13:42:25 -0700
• Engine revision 0545f8705d
• Dart version 3.1.5
• DevTools version 2.25.0
[√] Windows Version (Installed version of Windows is version 10 or higher)
[√] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
• Android SDK at C:\Users\User3\AppData\Local\Android\sdk
• Platform android-34, build-tools 34.0.0
• Java binary at: C:\Program Files\Android\Android Studio\jbr\bin\java
• Java version OpenJDK Runtime Environment (build 17.0.6+0-b2043.56-10027231)
• All Android licenses accepted.
[√] Chrome - develop for the web
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe
[√] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.7.6)
• Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Community
• Visual Studio Community 2022 version 17.7.34221.43
• Windows 10 SDK version 10.0.22621.0
[√] Android Studio (version 2022.3)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 17.0.6+0-b2043.56-10027231)
[√] VS Code (version 1.84.1)
• VS Code at C:\Users\User3\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.76.0
[√] Connected device (4 available)
• CPH2201 (mobile) • 192.168.0.243:5555 • android-arm64 • Android 13 (API
33)
• Windows (desktop) • windows • windows-x64 • Microsoft Windows
[Version 10.0.22621.2428]
• Chrome (web) • chrome • web-javascript • Google Chrome
118.0.5993.118
• Edge (web) • edge • web-javascript • Microsoft Edge
119.0.2151.58
! Device adb-SWVOFYZ9PVBAEY75-tt3xKO._adb-tls-connect._tcp. is offline.
[√] Network resources
• All expected network resources are available.
• No issues found!
Related issues / more information
#1611
Working on PR
no way
Update
It definitely has something to do with audioplayers_android 4.0.3. I downgrade both package and forced audioplayers_android package back to 4.0.2 and it worked fine again.
audioplayers: ^5.2.0 audioplayers_android: 4.0.2
Thanks for the report. Is there a reason to call play 15 times at the same time (even without await keyword). This doesn't make sense for me. You need a separate player for each source, if want to play them simultaneously. Also i != number. Do you want the same song multiple times, or different songs?
Thanks for the report. Is there a reason to call
play15 times at the same time (even withoutawaitkeyword). This doesn't make sense for me. You need a separate player for each source, if want to play them simultaneously. Alsoi != number. Do you want the same song multiple times, or different songs?
Hi, The function will have to loop every seconds. It's something to do with my internal hardware test for mobile phones. One of them is phone speaker. This function is supposed to repeated the same .mp3 sound while speaking something until it received respond from user. I set the countdown to 15 seconds hence the specific 15 loop.
The whole function is actually longer than that and even have Riverpod state. But it contain internal company code so i rather avoid showing it here. The main thing here is that my Flutter sample above that comes with the report definitely reproduce the issue so it's either the .mp3 file itself, or something else entirely.
But the loop is not async so you execute all the 15 plays at once, which probably causes the player to collapse.
And it's true, something changed in the last update, which may is responsible to cause the error, see: https://github.com/bluefireteam/audioplayers/commit/7ae3c9cda8c9b12d47572039c4ba3e83fada406c#diff-73c0547bd20d0db27baafc88e2e9439001dc1f3d792213a7784af04b273aa02fR125 It means, that now, the source is not set immediately and therefore the player could be set multiple times with the same source. So we may need to make this a synchronized block.
This means, yes, there is room for improvement, but I would blame the android MediaPlayer lib for that, as it shouldn't throw, like you wouldn't expect. We are planning to switch anyways, see #1526.
But also this test does not replicate any real world scenario: You have to provide a counter which is updating:
var playCounter = 0:
final player = AudioPlayer();
await player.setReleaseMode(ReleaseMode.stop);
await player.setSource(AssetSource(
'sound/one.mp3',
),
);
player.onPlayerComplete.listen((_) async {
if (playcounter >= 15) return;
playCounter++;
await player.stop();
await player.resume();
});
await player.resume();
Or just activate the loop mode and wait 15 seconds with Future.delayed and then stop the player:
AudioPlayer()..setReleaseMode(ReleaseMode.loop)
I'm not sure if the intention is to set a new source 15 times, even if it is the same for testing purposes. I have a use-case, where I have a global player - never gets disposed - and I have to set a new source after an audio is done playing (whatever state the AudioPlayer might be having). And I do get the error. I'm not fully done debugging, but I believe it is when I set a new source.
This issue was closed by the stale bot due to inactivity.
You need a separate player for each source, if want to play them simultaneously.
Hey, is this correct? I have several sounds that might play at the same time at a game, and I am using something like this:
on the init method: poolBalao = await AudioPool.create( source: AssetSource("sounds/som-balao-efeito-2.mp3"), maxPlayers: 3, minPlayers: 1, ); poolCheering = await AudioPool.create( source: AssetSource("sounds/kids-cheering.mp3"), maxPlayers: 3, minPlayers: 1, );
Then the methods:
Future<void> playEstouroBalaoEffect() async {
poolBalao.start();
}
the on the event:
onPop: () async { Vibration.vibrate( duration: 250, ); await playEstouroBalaoEffect(); ...
Is this creating a different player for each sound?