flutter - 多次播放同一个音频文件 - Audioplayers Flutter
问题描述
我怎样才能根据需要多次播放相同的音频文件,而不是循环播放,但我希望能够精确地播放多少次,我按照本教程制作了播放/暂停功能的基础知识。我正在与其他人作斗争。我使用了最新版本的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();
}
});
});
推荐阅读
- c - 了解堆栈分配的对象释放
- powershell - 偏执狂的多次 AES 256 迭代
- amazon-web-services - AWS 创建失败:服务已存在。(服务:AWSServiceDiscovery;状态代码:400;错误代码:ServiceAlreadyExists;请求 ID)
- python - QQ图在一个图中而不是9个子图python
- c# - Web.config 中的正则表达式重写部分小写 URL 的规则
- oauth-2.0 - Google OAuth 授权 URL 之间有什么区别
- azure - 天蓝色取消与删除订阅
- python - 使用 matplotlib 时,如何解决我的显示编号与条形图重叠的问题?
- vue.js - 在 vue 中将 const 变量重置为其默认值
- google-analytics - totals.visits = null 的 Session 和 Bounced Session 有什么区别?