dart just_audio -完成后的音频播放器,从头开始

4ktjp1zp  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(238)

我创建了播放器音频,并使用了just_audio插件,但音频播放器完成后无法返回到开头时出现了问题。我尝试使用player.playerStateStream.listen(),但当我单击播放图标时,它无法播放音频,开始持续时间也不会更改为0,但当我手动移动滑块时,它可以工作,如何解决此问题?

编辑:

我需要什么?
我需要音频完成后,滑块回到开始和重置持续时间,就像我第一次播放音频和暂停与onPressed播放音频的音频。

代码:

String currentTime = "", endTime = "";
double minDuration = 0, maxDuration = 0, currentDuration = 0;

void setAudio(String url) async {
    setState(() => isLoadAudio = true);
    await player.setUrl(url);
    currentDuration = minDuration;
    maxDuration = player.duration!.inMilliseconds.toDouble();
    setState(() {
      currentTime = getDuration(currentDuration);
      endTime = getDuration(maxDuration);
    });
    isPlaying = false;
    changeStatusPlaying();
    player.positionStream.listen((duration) {
      currentDuration = duration.inMilliseconds.toDouble();
      setState(() => currentTime = getDuration(currentDuration));
    });
    setState(() => isLoadAudio = false);
    player.playerStateStream.listen((state) {
      if (state.processingState == ProcessingState.completed) {
        setState(() {
          currentDuration = minDuration;
          if (isRepeating == true) {
            isPlaying = true;
          } else {
            isPlaying = false;
            isRepeating = false;
          }
        });
      }
    });
  }
void changeStatusPlaying() {
    setState(() => isPlaying = !isPlaying);
    isPlaying ? player.play() : player.pause();
    currentDuration == maxDuration ? isPlaying : !isPlaying;
  }

String getDuration(double value) {
    Duration duration = Duration(milliseconds: value.round());
    return [duration.inHours, duration.inMinutes, duration.inSeconds]
        .map((e) => e.remainder(60).toString().padLeft(2, "0"))
        .join(":");
  }

Slider(
   value: currentDuration,
   min: minDuration,
   max: maxDuration,
   onChanged: (v) {
     currentDuration = v;
     playAudio(currentDuration);
   },
),
cbeh67ev

cbeh67ev1#

将音频播放器设置为循环播放:

player.setLoopMode(LoopMode.one);

完整示例(将音频文件放在/assets/audio):

class MySimplePlayer extends StatefulWidget {
  final String name, asset;

  const MySimplePlayer(this.name, String filename)
      : this.asset = "assets/audio/$filename";

  @override
  _MySimplePlayerState createState() => _MySimplePlayerState();
}

class _MySimplePlayerState extends State<MySimplePlayer> {
  late AudioPlayer player;
  bool _ready = false;

  @override
  void initState() {
    super.initState();
    player = AudioPlayer();
    player.setLoopMode(LoopMode.one);    
    player.setAsset(widget.asset).then((_) {
      if (mounted) setState(() => _ready = true);
    });
  }

  @override
  void dispose() {
    player.stop();
    player.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!_ready) return const SizedBox();

    return Card(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          const SizedBox(width: 16),
          Expanded(child: Text(widget.name)),
          if (!player.playing)
            IconButton(
              icon: Icon(Icons.play_arrow),
              onPressed: () async {
                player.play();
                setState(() {});
              },
            ),
          if (player.playing)
            IconButton(
              icon: Icon(Icons.pause),
              onPressed: () async {
                await player.pause();
                setState(() {});
              },
            ),
          IconButton(
            icon: Icon(Icons.stop),
            onPressed: () async {
              await player.stop();
              setState(() {});
            },
          ),
          const SizedBox(width: 16),
        ],
      ),
    );
  }
}
j9per5c4

j9per5c42#

Try this:
        
bool _isPlaying = false;
bool _isCompleted = false;
Duration? _duration = Duration.zero;
Duration? _position = Duration.zero; 
                
After player has completed, move position to Duration(seconds: 0)   
                        
            Init state  
                            
                            @override
                              void initState() {
                                _initLoadFile();
                                // Listen player states
                                _audioPlayer.playerStateStream.listen((event) async {
                                  setState(() {
                                    _isPlaying = event.playing;
                                  });
                                  if (event.processingState == ProcessingState.completed) {
                                    setState(() {
                                      _isPlaying = false;
                                      _position = const Duration(seconds: 0);
                                      _isCompleted = true;
                                    });
                                  }
                                });
                                // Listen audio duration
                                _audioPlayer.durationStream.listen((newDuration) {
                                  setState(() {
                                    _duration = newDuration;
                                  });
                                });
                                // Listen audio position
                                _audioPlayer.positionStream.listen((newPosition) {
                                  setState(() {
                                    _position = newPosition;
                                  });
                                });
                                super.initState();
                              }
                            
                            
                    In widget
                            
                    ElevatedButton(
                                  onPressed: () async {
                                    if (!_isPlaying) {
                                      setState(() {
                                        _isPlaying = true;
                                        _isCompleted = false;
                                      });
                                      await _audioPlayer.play();
                                      if (_isCompleted) {
                                        await _audioPlayer.seek(const Duration(seconds: 0));
                                        await _audioPlayer.pause();
                                      }
                                    }
                                    if (_isPlaying) {
                                      setState(() {
                                        _isPlaying = false;
                                      });
                                      await _audioPlayer.pause();
                                    }
                                  },
                                  child: Icon(
                                    _isPlaying ? Icons.pause : Icons.play_arrow,
                                  ),
                                ),

相关问题