Search code examples
flutterdartsoundeffect

How to play sound on button press


I want to write an soundboard, basically a list of buttons and the job of each button is to play a sound that I have on my PC when they are pressed.

I've already done the design with a list view and some material buttons, but I don't know how to make them play sounds when I press them.


Solution

  • 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'),
          ),
        );
      }
    }