gpt4 book ai didi

flutter - 多次播放相同的音频文件-Audioplayers Flutter

转载 作者:行者123 更新时间:2023-12-03 00:23:08 65 4
gpt4 key购买 nike

我如何可以多次播放同一音频文件,而不是循环播放,但我希望能够精确地播放多少次,所以我遵循此tutorial进行了基础(即播放/暂停功能)。我正在为其余的工作而苦苦挣扎。
我使用了audioplayers软件包的最新版本。
这是我的代码:

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:audioplayers/audio_cache.dart';


class Player extends StatefulWidget {
@override
_PlayerState createState() => _PlayerState();
}

AnimationController _animationIconController ;

AudioCache audioCache;
AudioPlayer audioPlayer;


bool issongplaying = false;
bool isplaying = false;



class _PlayerState extends State<Player> with TickerProviderStateMixin {
@override
void initState() {
// TODO: implement initState
super.initState();
initPlayer();
}

void initPlayer(){
_animationIconController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 750),
reverseDuration: Duration(milliseconds: 750),
);
audioPlayer = new AudioPlayer();
audioCache = new AudioCache(fixedPlayer: audioPlayer);

}


@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
GestureDetector(
onTap: (){
setState((){
isplaying
? _animationIconController.reverse()
: _animationIconController.forward();
isplaying = !isplaying;
});

if (issongplaying == false) {
audioCache.play('audio.wav');
setState(() {
issongplaying = true;
});
} else {
audioPlayer.pause();
setState(() {
issongplaying = false;
});
}
},
child: ClipOval(
child: Container(
decoration: BoxDecoration(
border: Border.all(
width: 2,
color: Colors.greenAccent,
),
borderRadius: BorderRadius.all(Radius.circular(50.0)
),
),
width: 75,
height: 75,
child: Center(
child: AnimatedIcon(
icon: AnimatedIcons.play_pause,
progress: _animationIconController,
color: Colors.grey,
size: 60,
)
),
),
),
)
],
),
),
);
}
}
谢谢

最佳答案

这对您来说可能很复杂,但请尝试一下。
我可以看到audioplayers包中有一个onPlayerCompletion事件,该事件在您每次播放完音频后都会被调用。
您可以告诉播放器此事件,以跟踪其结束的时间并将音频设置为循环播放,当它重复X次时,它将停止播放:

int timesPlayed = 0;
int timesToRepeat = 3; //The audio will repeat 3 times

//This method gets called each time your audio finishes playing.
player.onPlayerCompletion.listen((event) {
//Here goes the code that will be called when the audio finishes
onComplete();
setState(() {
position = duration;
timesPlayed++;
if(timesPlayed >= timesToRepeat) {
timesPlayed = 0;
await player.stop();
}
});
});

关于flutter - 多次播放相同的音频文件-Audioplayers Flutter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64481121/

65 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com