How to play sound on button press

Add audioplayers as a dependency and your audio file to pubspec.yaml file like this:

dependencies:
  audioplayers: ^1.0.1

flutter: 
  assets:
    - assets/audio/my_audio.mp3

Full code (Null-safe):

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ElevatedButton(
        onPressed: () => AudioPlayer().play(AssetSource('audio/my_audio.mp3'));
        child: Text('Play'),
      ),
    );
  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)