How to play a custom sound in Flutter?

后端 未结 4 1222
感动是毒
感动是毒 2020-12-24 12:29

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

SystemSound.play(SystemSoundType.click);

How can I play a customized sound?

L

4条回答
  •  失恋的感觉
    2020-12-24 13:08

    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 assets folder. It does not work when it is in a sub folder. For example, something like: - assets/sounds/yes.mp3 will not work. Just put your audio file in the assets folder not in its sub folder

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

    (4) then define this function:

    Future 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();

提交回复
热议问题