42

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

Jako
  • 2,489
  • 3
  • 28
  • 38

6 Answers6

52

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 AudioPlayer player = new AudioPlayer();
const alarmAudioPath = "sound_alarm.mp3";
player.play(alarmAudioPath);

An example here

ubershmekel
  • 11,864
  • 10
  • 72
  • 89
Valentina Konyukhova
  • 4,464
  • 2
  • 24
  • 33
24

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();
    });
  }
}
Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
10

The audioplayers works (from https://medium.com/@bennett4/adding-custom-sound-effects-to-a-flutter-mobile-app-41594f1f3305):

(1) Add the library to your pubspec.yaml: audioplayers: ^0.15.1

(2) In pubspec.yaml under flutter add the reference to your assets file:

flutter
    assets:
       - assets/yes.mp3

MAKE SURE it is under the assets folder. It does not work when it is in a subfolder. For example, something like: - assets/sounds/yes.mp3 will not work. Just put your audio file in the assets folder, not in its subfolder

(3) import the library in your app as: import package:audioplayers/audioplayers.dart;

(4) then define this function:

Future<AudioPlayer> playLocalAsset() async {
    AudioCache cache = new AudioCache();
   //At the next line, DO NOT pass the entire reference such as assets/yes.mp3. This will not work.
   //Just pass the file name only.
    return await cache.play("yes.mp3"); 
}

(5) call the function whenever you need to play a sound: await playLocalAsset();

Hardik
  • 373
  • 2
  • 14
DK250
  • 1,064
  • 13
  • 11
6

Null-safe code:

  1. Add dependency to your pubspec.yaml file,

    dependencies:
      audioplayers: ^0.19.0
    
  2. Add audio file path to your pubspec.yaml file.

    flutter: 
      assets:
        - assets/audio/my_audio.mp3
    
  3. Run flutter pub get

Full code:

class HomePage extends StatelessWidget {
  final AudioCache _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 Audio'),
      ),
    );
  }
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
2

[Answer updated: this approach doesn't work, see comments] You can use the video_player plugin maintained by the Flutter team. It can reproduce many kinds of media across platforms, including sound files. More specifically, you may want to use the the VideoPlayerController class.

eg.

   _controller = VideoPlayerController.network('https://www.example.com/soundsFile.wav');
   _controller.play();
eldermao
  • 633
  • 8
  • 18
  • OP asked for mp3, does this plugin play that? – iDecode May 21 '20 at 12:38
  • Nevermind, I realized that the fact that this happens to work for some audio files on Android doesn't mean that the plugin supports audio playback. I found out the hard way that this plugin is unable to play audio on iOS. And there is no plan to make it work since that's not the purpose of the `video_player` plugin. The suggested approach in the community is to use `just_audio` by @ryanheise instead. – eldermao May 21 '20 at 17:01
  • @iKeepChangingName Yes, [just_audio](https://pub.dev/packages/just_audio) does play mp3 and it works well. – eldermao May 27 '20 at 17:45
2

You can use just_audio package.

To play sound from a local file... Follow the steps :-

  1. Run flutter pub add just_audio in your terminal
  2. import 'package:just_audio/just_audio.dart'; -> Import package in your file
  3. AudioPlayer player = AudioPlayer(); -> Create the object
  4. player.setAsset('path_to_your_audiofile'); -> Set the path to your audio asset
  5. player.play(); -> Play the audio

Here is a sample method implementing this :-

void playSampleSound() async {
     AudioPlayer player = AudioPlayer();
    await player.setAsset('assets/audio/sample_audio.mp3');
    player.play();
  }

Thanks