Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a custom sound in Flutter?

Tags:

flutter

dart

I was able to play a simple sound with this line of code:

SystemSound.play(SystemSoundType.click); 

How can I play a customized sound?

Let's say a short mp3

like image 494
Jako Avatar asked May 05 '17 20:05

Jako


People also ask

How do you add custom sounds to Flutter?

If you want to add custom sound effects to your Flutter application, you can use AudioPlayers. AudioPlayers Flutter package that allows developers to easily add sound effects to their applications. It will provide various options such as play/pause, loop, search, and other methods.

How do you play sound from assets in Flutter?

How to add & use assets audio player package in flutter. Open your flutter project & navigate to pubspec. yaml file & open it, then under dependencies add the audio player package. then don't forget to hit pub get button, it will download the package in your flutter project.

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.


2 Answers

Simple solution for playing a file already defined in assets is using AudioCache. Library: https://pub.dartlang.org/packages/audioplayers. More about AudioCache After adding library to pubspec.yaml, import required class:

import 'package:audioplayers/audio_cache.dart'; 

add an asset in the same file and place the file with sound to assets folder (if you don't have this folder, create it)

assets: - assets/sound_alarm.mp3 

then add this code:

static AudioCache player = new AudioCache(); const alarmAudioPath = "sound_alarm.mp3"; player.play(alarmAudioPath); 

An example here

like image 158
Valentina Konyukhova Avatar answered Sep 22 '22 20:09

Valentina Konyukhova


Thanks for checking out Flutter!

Flutter SDK today (as of May 5, 2017) doesn't have built-in support to play and control arbitrary audio. However, we designed our plugin system to support it.

This plugin adds audio support to Flutter: https://pub.dartlang.org/packages/audioplayer

From the plugin's README:

Future play() async {   final result = await audioPlayer.play(kUrl);   if (result == 1) setState(() => playerState = PlayerState.playing); }  // add a isLocal parameter to play a local file Future playLocal() async {   final result = await audioPlayer.play(kUrl);   if (result == 1) setState(() => playerState = PlayerState.playing); }   Future pause() async {   final result = await audioPlayer.pause();   if (result == 1) setState(() => playerState = PlayerState.paused); }  Future stop() async {   final result = await audioPlayer.stop();   if (result == 1) {     setState(() {       playerState = PlayerState.stopped;       position = new Duration();     });   } } 
like image 33
Seth Ladd Avatar answered Sep 18 '22 20:09

Seth Ladd