如何在Flutter中播放自定义声音?

Jak*_*ako 15 dart flutter

我能够在这行代码中播放一个简单的声音:

SystemSound.play(SystemSoundType.click);
Run Code Online (Sandbox Code Playgroud)

如何播放自定义声音?

让我们说一个简短的mp3

Val*_*ova 24

播放已在资产中定义的文件的简单解决方案是使用AudioCache.图书馆:https://pub.dartlang.org/packages/audioplayers. 有关AudioCache的更多信息 添加库后pubspec.yaml,导入所需的类:

import 'package:audioplayers/audio_cache.dart';
Run Code Online (Sandbox Code Playgroud)

在同一文件中添加资源并将带声音的文件放到assets文件夹中(如果没有此文件夹,则创建它)

assets:
- assets/sound_alarm.mp3
Run Code Online (Sandbox Code Playgroud)

然后添加此代码:

static AudioCache player = new AudioCache();
const alarmAudioPath = "sound_alarm.mp3";
player.play(alarmAudioPath);
Run Code Online (Sandbox Code Playgroud)

这里有一个例子


Set*_*add 13

感谢您查看Flutter!

Flutter SDK今天(截至2017年5月5日)没有内置支持来播放和控制任意音频.但是,我们设计了我们的插件系统来支持它.

此插件为Flutter添加了音频支持:https://pub.dartlang.org/packages/audioplayer

从插件的自述文件:

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();
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 2020 年 2 月,Flutter 本身仍然没有支持。很好,他们发布了一个异国情调的“本周小部件”,但这太基础了,不能成为图书馆的标准。 (3认同)
  • 一年后关于这个问题有什么消息吗? (2认同)

DK2*_*250 10

音频播放器有效(来自https://medium.com/@bennett4/adding-custom-sound-effects-to-a-flutter-mobile-app-41594f1f3305):

(1) 将库添加到 pubspec.yaml 中:audioplayers: ^0.15.1

(2) 在 pubspec.yaml 下flutter添加对资产文件的引用:

flutter
    assets:
       - assets/yes.mp3
Run Code Online (Sandbox Code Playgroud)

确保它位于资产文件夹下。当它位于子文件夹中时它不起作用。例如,类似: - asset/sounds/yes.mp3 将不起作用。只需将音频文件放入 asset 文件夹中,而不是其子文件夹中

(3) 将库导入到您的应用程序中:import package:audioplayers/audioplayers.dart;

(4)然后定义这个函数:

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"); 
}
Run Code Online (Sandbox Code Playgroud)

(5) 每当需要播放声音时调用该函数:await playLocalAsset();


Cop*_*oad 6

空安全代码:

  1. 将依赖项添加到您的pubspec.yaml文件中,

    dependencies:
      audioplayers: ^0.19.0
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将音频文件路径添加到您的pubspec.yaml文件中。

    flutter: 
      assets:
        - assets/audio/my_audio.mp3
    
    Run Code Online (Sandbox Code Playgroud)
  3. 跑步flutter pub get

完整代码:

dependencies:
  audioplayers: ^0.19.0
Run Code Online (Sandbox Code Playgroud)