Flutter: Play sound on button press

If you just want to play the music when someone pressed on the button then you can follow these steps:-

1. Add dependency

dependencies:
      audioplayers: ^0.10.0

then run the following command in your terminal to get the newly added package -

flutter packages get

2. Import it into main.dart or the file where you want to use it.

import 'package:audioplayers/audio_cache.dart'; 

There two classes that you can import AudioPlayer or AudioCache and to play local files AudioCache will be used.

3. Create an Object of AudioCache

 final player = AudioCache();

4. Use play() method to play you audio

player.play('note1.wav');

Note - note1.wav is stored inside assets folder in my main directory and you don't have to mention it while using the play() method.

Example code -

    import 'package:audioplayers/audio_cache.dart';
    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      final player = AudioCache();

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: SafeArea(
              child: FlatButton(
                child: Text("play "),
                onPressed: () {
                  player.play('note1.wav');
                },
              ),
            ),
          ),
        );
      }
    }

For anyone who needs to play a "click" sound:

import 'package:flutter/services.dart';
SystemSound.play(SystemSoundType.click);

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

Tags:

Dart

Flutter