我有一个在GridView中有100个编号按钮的应用程序。我想播放相应的歌曲(名为f。即“87.mp3”)。我的AudioPlayer代码的开头看起来像这样:
class AudioPlayer extends StatefulWidget {
final String audioPath;
const AudioPlayer({super.key, required this.audioPath});
@override
_AudioPlayerState createState() => _AudioPlayerState();
}
class _NewCustomWidgetState extends State<AudioPlayer>
with WidgetsBindingObserver {
final _player = AudioPlayer();
@override
void initState() {
super.initState();
ambiguate(WidgetsBinding.instance)!.addObserver(this);
_init();
}
Future<void> _init() async {
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.speech());
_player.playbackEventStream.listen((event) {},
onError: (Object e, StackTrace stackTrace) {
print('A stream error occurred: $e');
});
try {
await _player.setAsset(widget.audioPath);
print("Audio asset is set.");
} catch (e) {
print("Error loading audio source: $e");
}
}
@override
void dispose() {
ambiguate(WidgetsBinding.instance)!.removeObserver(this);
_player.dispose();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.paused) {
_player.stop();
}
}
Stream<PositionData> get _positionDataStream =>
Rx.combineLatest3<Duration, Duration, Duration?, PositionData>(
_player.positionStream,
_player.bufferedPositionStream,
_player.durationStream,
(position, bufferedPosition, duration) => PositionData(
position, bufferedPosition, duration ?? Duration.zero));
@override
Widget build(BuildContext context) {...}}
AudioPlayer将audioPath作为参数。它会注意到audioPath发生了变化,但不会更新自己,因此它会播放初始化时设置的同一首歌曲。
1条答案
按热度按时间sqserrrh1#
在更新状态后尝试这个,不要担心,因为你的代码处理音频播放器作为一个singlton,你设置为去