How to play sound on button press
Asked Answered
S

7

34

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.

Saltatorial answered 30/5, 2019 at 12:1 Comment(0)
T
48

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'),
      ),
    );
  }
}
Tollefson answered 30/5, 2019 at 12:19 Comment(8)
error: The method 'initState' isn't defined in a superclass of 'MyApp'.Saltatorial
error: The method 'AudioCache' isn't defined for the class '_HomePageState'.Saltatorial
import 'package:audioplayers/audio_cache.dart'; at the top of your file.Tollefson
My problem was that I didn't worked with Stateful widgets beforeSaltatorial
import 'package:audioplayers/audio_cache.dart'; import 'package:audioplayers/audioplayers.dart';Domesday
I needed to change this line to include 'assets' in the path... _audioCache = AudioCache(prefix: "assets/audio/", fixedPlayer: AudioPlayer()..setReleaseMode(ReleaseMode.STOP));Schwann
in my case, needed to completely stop and start app for it to work (restarting not sufficient).Beene
Make sure u don't have 'assets' in the file path. It'll work.Cowes
F
17

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

import 'package:flutter/services.dart';
SystemSound.play(SystemSoundType.click);
Ferri answered 16/8, 2021 at 11:57 Comment(1)
simple and straightforwardScrewdriver
A
13

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');
                },
              ),
            ),
          ),
        );
      }
    }
Analyst answered 24/7, 2020 at 1:44 Comment(2)
If anybody has issues with this implementation, I had to stop the app and restart it. Hot reload/restart was not enough.Chinchilla
Thank you so much for providing a full, working example :-)Neurovascular
F
8

For repeated sounds I recommend soundpool package.
From my experience, it provides better latency, i.e. lower delay between trigger action and actual sound play.
Here's code example (copied from the package's readme):

    import 'package:soundpool/soundpool.dart';

    Soundpool pool = Soundpool(streamType: StreamType.notification);
    int soundId = await rootBundle.load("sounds/dices.m4a").then((ByteData soundData) {
                  return pool.load(soundData);
                });
    int streamId = await pool.play(soundId);
Farrahfarrand answered 2/10, 2020 at 15:29 Comment(2)
this code was the only that worked for me... i waste a lot of hours searching. Thanks!Spinal
Perfect solution for playing sounds with lower delay.Drynurse
S
3

Using Flutter 3.0.3, Dart 2.17.5, and DevTools 2.12.2:

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

dependencies:
  audioplayers: any

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

An minimal working code, based on the default example of the Android Studio Ide (Null-safe):

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  final player = AudioPlayer();

  void _incrementCounter() {
    player.play(AssetSource('audio/my_audio.mp3'));
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
Sommelier answered 26/6, 2022 at 17:10 Comment(0)
C
2

First of all you have to create a directory in main project folder name as 'assets' where all music are stored. I have 7 music, like note1.wav, note2.wav ..... note7.wav.

Assets

assets:
     - assets/

Dependencies,

dependencies:
  audioplayers: ^0.10.0

main.dart code

import 'package:audioplayers/audio_cache.dart';
import 'package:flutter/material.dart';

void main() => runApp(Xylophone());

class Xylophone extends StatefulWidget {
  @override
  _XylophoneState createState() => _XylophoneState();
}

class _XylophoneState extends State<Xylophone> {
  
// music play sound number function, like note1.wav, note2.wav etc.
  void playSound(int number){
    final player = AudioCache();
    player.play('note$number.wav');
  }
// Expanded Widget Function Used for repeated Code
 Expanded buildKey(int soundNum, Color color){
   return Expanded(
     child: FlatButton(
       color: color,
       onPressed: (){
         playSound(soundNum);
       },
       child: Text(""),
     ),
   );
 }
  @override
  Widget build(BuildContext context) {
    // var buttonHeight = MediaQuery.of(context).size.height/2;
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Scaffold(
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              buildKey(1, Colors.red),
              buildKey(2, Colors.green),
              buildKey(3, Colors.blue),
              buildKey(4, Colors.deepPurpleAccent),
              buildKey(5, Colors.redAccent),
              buildKey(6, Colors.black54),
              buildKey(7, Colors.pink),
            ],
          ),
        ),
      ),
    );
  }
}
Cockadoodledoo answered 21/12, 2020 at 19:55 Comment(0)
B
1

For anyone looking for a simple solution for playing "beep"sounds or custom android/ios sounds you can try "flutter_beep".

link: https://pub.dev/packages/flutter_beep

I couldn't make audioplayers work (because of other packages i am already using I believe) but this flutter_beep was easy to set up and worked.

Add it to your pubspec.yaml and insert it in your code like so:

import 'package:flutter_beep/flutter_beep.dart';

RaisedButton( child: Text("Beep Success"), onPressed: ()=> FlutterBeep.beep()),
RaisedButton( child: Text("Beep Fail"), onPressed: ()=> FlutterBeep.beep(false)),
RaisedButton( child: Text("Beep Android Custom"), onPressed: ()=> FlutterBeep.playSysSound(AndroidSoundIDs.TONE_CDMA_ABBR_ALERT)),
RaisedButton( child: Text("Beep somthing"), onPressed: ()=> FlutterBeep.playSysSound(41)),
RaisedButton( child: Text("Beep iOS Custom"), onPressed: ()=> FlutterBeep.playSysSound(iOSSoundIDs.AudioToneBusy)),
Batts answered 5/5, 2022 at 5:38 Comment(1)
This is a good answer in light of this: github.com/flutter/flutter/issues/57531Feltie

© 2022 - 2024 — McMap. All rights reserved.