サイトアイコン ぼちぼち凡才ITエンジニアのブログ

Flutterで音が再生できないエラー「AudioPlayerException」の解決法

事象

以下のソースコードのように、assetsフォルダ内の.mp3ファイルを再生しようとしたらエラーが発生し再生できない。

final AudioPlayer _audioPlayer = AudioPlayer();
...(中略)...
_audioPlayer.setSource(AssetSource('assets/notification.mp3'));

エラーメッセージは下記の通り

AudioPlayers Exception: AudioPlayerException(
        AssetSource(path: assets/notification.mp3, mimeType: null), 
        PlatformException(WebAudioError, Failed to set source. For troubleshooting, see
        https://github.com/bluefireteam/audioplayers/blob/main/troubleshooting.md, MediaError: MEDIA_ELEMENT_ERROR: Format error (Code: 4),
        null)
RethrownDartError: PlatformException(WebAudioError, Failed to set source. For troubleshooting, see
(h)ttps://github.com/bluefireteam/audioplayers/blob/main/troubleshooting.md, MediaError: MEDIA_ELEMENT_ERROR: Format error (Code: 4),
null)

対処法

ただ、AssetSourceassetsという部分が不要なので削除するだけで良かった。

// 変更前
_audioPlayer.setSource(AssetSource('assets/notification.mp3'));

// 変更後
_audioPlayer.setSource(AssetSource('notification.mp3'));

原因

ネット上の記事やChatGPTのコードを参考にしすぎたためか、不要な部分が含まれてしまったと思うので反省します。

参考

モバイルバージョンを終了