我的代码发生的情况是,当我第一次单击按钮时,音频会播放,但如果我再次单击,音频不会播放。这里有什么问题?我想在每次单击按钮时播放音频文件。这是我的代码-
import 'package:just_audio/just_audio.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late AudioPlayer player;
@override
void initState() {
super.initState();
player = AudioPlayer();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async {
await player.setAsset('assets/Audios/win.wav');
player.play();
},
child: const Text('Win'),
),
],
),
),
),
);
}
}
我正在Windows平台的Flutter框架中构建这个应用程序just_audio的依赖项添加到pubspec.yaml文件中,音频文件存储在assets/Audios目录下。
尝试下面的代码,希望对您有所帮助。此处使用assets_audio_player
包
您的功能:
playSound() async {
AssetsAudioPlayer audioPlayer = AssetsAudioPlayer();
await audioPlayer.open(
Audio(
'assets/bells.mp3',
),
);
}
您的小工具:
ElevatedButton(
onPressed: () => playSound(),
child: Text(
'Play',
),
),