Audio requires use of a plugin, luckily there are several, which should make it easier.
We are going to start by creating a basic Flutter app, the way we’ve done before. Then removing the comments. We’re going to play a small clip each time someone clicks on the increment button.
Installing the Plugin
Next we will need to install the plugin. That will require us going into the pubspec.yaml file to add the dependency.
Add the following line under dependencies. Remember, yaml is space sensitive, and it needs to be on the same indention level as flutter:
audioplayers: ^0.20.1
While we’re in the pubspec.yaml file, we’re going to add a reference for a small audio clip. I found a free clip at https://www.dreamstime.com/stock-music-sound-effect/ding.html which you can find as well. Download, and save it to a sub folder called assets. I named my file ding.mp3.
assets:
- assets/ding.mp3
We can then save and close the yaml file.
Finally we are going to go back into the main.dart file, and import the new library.
import 'package:audioplayers/audioplayers.dart';
Initializing the Audio File
We are going to create an object inside of the _MyHomePageState
class as an instance variable.
Since we’re looking for something nearly instantaneous, we’re going to use a lower quality initialization.
AudioPlayer _audioPlayer = AudioPlayer(mode: PlayerMode.LOW_LATENCY);
Calling to Play
Since we’re going to play whenever a click is made, we will update the _increment
method.
We’ve already got the object created, we just need to call the option to play.
int result = await _audioPlayer.play("assets/ding.mp3", isLocal: true);
Notice how there is an isLocal
property passed to the play
method. This is because our file is local, and is not needed if the file comes in from a URL.
Playing Audio in Flutter was originally found on Access 2 Learn