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

时间:2017-05-05 20:35:45

标签: dart flutter

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

SystemSound.play(SystemSoundType.click);

如何播放自定义声音?

让我们说一个简短的mp3

4 个答案:

答案 0 :(得分:11)

播放音频资产中已定义文件的简单解决方案是使用AudioCache。 库:https://pub.dartlang.org/packages/audioplayersMore about AudioCache 将库添加到import 'package:audioplayers/audio_cache.dart'; 后,导入所需的类:

assets:
- assets/sound_alarm.mp3

在同一文件中添加资产,然后将带有声音的文件放置到Assets文件夹中(如果没有此文件夹,则创建它)

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

然后添加此代码:

{{1}}

示例here

答案 1 :(得分:1)

[答案已更新:此方法无效,请参阅评论] 您可以使用Flutter小组维护的video_player插件。它可以跨平台重现多种媒体,包括声音文件。更具体地说,您可能要使用VideoPlayerController类。

例如

   _controller = VideoPlayerController.network('https://www.example.com/soundsFile.wav');
   _controller.play();

答案 2 :(得分:1)

音频播放器正常工作(来自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

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

(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"); 
}

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

答案 3 :(得分:0)

空安全代码:

  1. 向您的 pubspec.yaml 文件添加依赖项

    dependencies:
      audioplayers: ^0.19.0
    
  2. 将音频文件路径添加到您的 pubspec.yaml 文件。

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

完整代码:

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'),
      ),
    );
  }
}