我尝试在 onPressed() 上播放本地 mp3 音频文件
函数如下所示:
playLocal() async {
await audioPlayer.play('assets/audio/test.mp3', isLocal: true);
}
文件位于此处:
pubspec.yaml:
flutter:
uses-material-design: true
assets:
- assets/audio/test.mp3
音频播放器错误:
[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: PlatformException(Unexpected error!, Unable to access resource, java.lang.RuntimeException: Unable to access resource
答案 0 :(得分:0)
这是我正在使用的课程。
import 'dart:io';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';
void audioPlayerHandler(AudioPlayerState value) => null;
class PlaySound {
final AudioPlayer _audioPlayer = AudioPlayer(mode: PlayerMode.LOW_LATENCY);
final AudioCache _audioCache = AudioCache();
static PlaySound _instance;
static PlaySound get instance {
_instance ??= PlaySound._init();
return _instance;
}
PlaySound._init();
void playLocalAsset({String sound}) async {
if (!kIsWeb && Platform.isIOS) {
//https://stackoverflow.com/questions/61263458/flutter-fatal-error-callback-lookup-failed-with-audioplayers-package
await _audioPlayer.monitorNotificationStateChanges(audioPlayerHandler);
}
if (_audioCache != null) {
await _audioCache.play(sound);
}
}
void playFromUrl({String url}) async {
await _audioPlayer.play(url);
}
}
这是 pubspec.yaml
assets:
- assets/sound/
就这样称呼它:
await PlaySound.instance.playLocalAsset(sound: 'sound/yourfile.mp3');