Reputation: 599
What happens with my code is that, when I click the button for the first time, the audio plays but if I click it again, the audio does not play. What is the problem here? I want to play the audio file every time I click the button. Here is my code-
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'),
),
],
),
),
),
);
}
}
I am building this application in Flutter framework for Windows platform. 'just_audio' dependency is added in the pubspec.yaml file and the audio file is stored under assets/Audios directory.
Upvotes: 2
Views: 3004
Reputation: 14885
Try below codde hope its helpful to you. Use assets_audio_player
package here
your function:
playSound() async {
AssetsAudioPlayer audioPlayer = AssetsAudioPlayer();
await audioPlayer.open(
Audio(
'assets/bells.mp3',
),
);
}
Your Widget:
ElevatedButton(
onPressed: () => playSound(),
child: Text(
'Play',
),
),
Upvotes: 2