有没有办法更新AudioPlayer的音频源,使其可以播放不同的歌曲(Flutter)?

ijxebb2r  于 2023-10-22  发布在  Flutter
关注(0)|答案(1)|浏览(107)

我有一个在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发生了变化,但不会更新自己,因此它会播放初始化时设置的同一首歌曲。

sqserrrh

sqserrrh1#

在更新状态后尝试这个,不要担心,因为你的代码处理音频播放器作为一个singlton,你设置为去

@override
void didUpdateWidget(covariant AudioPlayer oldWidget) {
  super.didUpdateWidget(oldWidget);
  
  // Check if the audioPath has changed
  if (oldWidget.audioPath != widget.audioPath) {
    // The audioPath has changed. We need to update the audio player.
    _init();
  }
}

相关问题