'Flutter: Play sound on button press
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?
Solution 1:[1]
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'),
),
);
}
}
Solution 2:[2]
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');
},
),
),
),
);
}
}
Solution 3:[3]
For anyone who needs to play a "click" sound:
import 'package:flutter/services.dart';
SystemSound.play(SystemSoundType.click);
Solution 4:[4]
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);
Solution 5:[5]
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),
],
),
),
),
);
}
}
Solution 6:[6]
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)),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Sludge |
Solution 3 | Ilya Iksent |
Solution 4 | Slava Medvediev |
Solution 5 | |
Solution 6 | Jeremie Houet |