我正在尝试在Flutter中构建一个音频播放器。我使用的是audioplayers
软件包。
我有一个音频播放器类,代码如下:
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
class MyAudio extends ChangeNotifier{
Duration totalDuration;
Duration position;
String audioState;
final String url;
MyAudio(this.url){
initAudio();
}
AudioPlayer audioPlayer = AudioPlayer();
initAudio(){
audioPlayer.onDurationChanged.listen((updatedDuration) {
totalDuration = updatedDuration;
notifyListeners();
});
audioPlayer.onAudioPositionChanged.listen((updatedPosition) {
position = updatedPosition;
notifyListeners();
});
audioPlayer.onPlayerStateChanged.listen((playerState) {
if(playerState == AudioPlayerState.STOPPED)
audioState = "Stopped";
if(playerState==AudioPlayerState.PLAYING)
audioState = "Playing";
if(playerState == AudioPlayerState.PAUSED)
audioState = "Paused";
notifyListeners();
});
}
playAudio(){
audioPlayer.play(url);
}
pauseAudio(){
audioPlayer.pause();
}
stopAudio(){
audioPlayer.stop();
}
seekAudio(Duration durationToSeek){
audioPlayer.seek(durationToSeek);
}
}
正如您所看到的,有一个名为url的参数,每当从播放列表中挑选歌曲时,我都想传递该变量。然而,我使用的这款播放器有一个类似Consumer
的:
Consumer<MyAudio>(
builder:(_,myAudioModel,child) => Slider(...)
在这种情况下,我无法传递URL
参数,我应该如何使用Consumer才能显式传递URL
参数?
MyAudio
通知程序在应用程序中被视为单个依赖项。如果您想更改当前url,请在play
方法中作为参数传递并调用:
class MyAudio extends ChangeNotifier{
Duration totalDuration;
Duration position;
String audioState;
MyAudio(){
initAudio();
}
AudioPlayer audioPlayer = AudioPlayer();
initAudio(){
audioPlayer.onDurationChanged.listen((updatedDuration) {
totalDuration = updatedDuration;
notifyListeners();
});
audioPlayer.onAudioPositionChanged.listen((updatedPosition) {
position = updatedPosition;
notifyListeners();
});
audioPlayer.onPlayerStateChanged.listen((playerState) {
if(playerState == AudioPlayerState.STOPPED)
audioState = "Stopped";
if(playerState==AudioPlayerState.PLAYING)
audioState = "Playing";
if(playerState == AudioPlayerState.PAUSED)
audioState = "Paused";
notifyListeners();
});
}
playAudio(String url){
audioPlayer.play(url);
}
pauseAudio(){
audioPlayer.pause();
}
stopAudio(){
audioPlayer.stop();
}
seekAudio(Duration durationToSeek){
audioPlayer.seek(durationToSeek);
}
}
消费者:
Consumer<MyAudio>(
builder:(_,myAudioModel,child) {
myAudioModel.play("MyUrl");
return MyWidget();
}),
或者,如果您有一个处理播放操作的回调:
```dart
Consumer<MyAudio>(
builder:(_,myAudioModel,child) {
return MyWidget(
onPressed: () => myAudioModel.play("MyUrl"),
// ...
);
}),