Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Play sound on button press

Tags:

flutter

dart

I'm very new to programing and especially flutter. 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. Can some one help me?

like image 735
Hurjui Ionut Avatar asked May 30 '19 12:05

Hurjui Ionut


People also ask

What procedure do you call in order to play a sound in Android?

mediaPlayer. start(); mediaPlayer. pause(); On call to start() method, the music will start playing from the beginning.

What is the sound of Flutter?

Irregularities that occur at higher frequencies are called flutter and cause a roughening of the tone: a piano sounds like a harp, and voices waver with small, rapid variations above and below proper pitch.


1 Answers

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

Full code (Null-safe):

class _HomePageState extends State<HomePage> {
  late final AudioCache _audioCache;

  @override
  void initState() {
    super.initState();
    _audioCache = AudioCache(
      prefix: 'audio/',
      fixedPlayer: AudioPlayer()..setReleaseMode(ReleaseMode.STOP),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ElevatedButton(
        onPressed: () => _audioCache.play('my_audio.mp3'),
        child: Text('Play'),
      ),
    );
  }
}
like image 80
CopsOnRoad Avatar answered Sep 24 '22 07:09

CopsOnRoad