gpt4 book ai didi

How to play a custom sound in Flutter?(如何在扑打中播放自定义声音?)

翻译 作者:bug小助手 更新时间:2023-10-26 21:52:15 25 4
gpt4 key购买 nike



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

让我们说一小段mp3


更多回答

github.com/flutter/flutter/issues/7482

Githorb.com/fltter/fltter/Issues/7482

I couldn't manage to play the system sound. I get the following message in debug output: "from settings cache , name = sound_effects_enabled , value = 0". Any idea what is missing?

我无法播放系统的声音。我在调试输出中得到以下消息:“从设置缓存,名称=声音_效果_启用,值=0”。知道遗失了什么吗?

优秀答案推荐

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:

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


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

下面是一个例子



Thanks for checking out Flutter!

感谢您收看Fflight!



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.

目前(截至2017年5月5日)Ffltter SDK尚不具备播放和控制任意音频的内置支持。然而,我们设计了我们的插件系统来支持它。



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

此插件为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();
});
}
}


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

音频播放器的工作原理(来自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

(1)将库添加到pubspec。yaml:audioplayer:^0.15.1


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

(2)在fltter下的pubspec.yaml中,添加对资源文件的引用:


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

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


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

(3)在您的APP中导入库为:导入包:AudioPlayers/AudioPlayers.dart;


(4) then define this function:

(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) call the function whenever you need to play a sound: await playLocalAsset();

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



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


[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.

[答案更新:此方法不起作用,见评论]您可以使用扑翼团队维护的VIDEO_PLAYER插件。它可以跨平台复制多种媒体,包括声音文件。更具体地说,您可能希望使用VideoPlayerControl类。



eg.

例如。

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



You can use just_audio package.

您可以使用Just_Audio包。


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

谢谢



You should give a try to https://pub.dev/packages/audioplayers

你应该试一试https://pub.dev/packages/audioplayers


First add

第一次添加


dependencies:
audioplayers: ^5.1.0

flutter:
assets:
- assets/
- assets/icon/
- assets/sound/

Then may i suggest to use a service

那么我可以建议使用一项服务吗?


class AudioService {

AudioService._();

static final AudioService _instance = AudioService._();

factory AudioService() {
return _instance;
}

void playSound(AssetSource assetSource) async{
AudioPlayer().play(assetSource, mode: PlayerMode.lowLatency); // faster play low latency eg for a game...
}
}

Then use assets as const

然后使用资源作为常量


class Constants{
static final AssetSource sound = AssetSource('sound/mysound.mp3');
}

Finally, the code to call the sound

最后,调用声音的代码


AudioService().playSound(Constants.sound );

更多回答

The library doesn't get imported

库不会被导入

Did you add audioplayers: ^0.13.7 to dependencies in pubspec.yaml?

是否在pubspec.yaml中将AudioPlayers:^0.13.7添加到依赖项中?

Yes I did and clicked packages get .But Import statement not detected stating "Target of Uri doesn't exist"

是的,我做了,并且点击了程序包得到。但是没有检测到说明“目标的URI不存在”的导入语句

I was getting the same error . After adding the dependencies and importing the library run the "flutter packages get" command and then close the VS code.This literally solves the error.

我也收到了同样的错误。在添加依赖项并导入库之后,运行“Ffltter Packages Get”命令,然后关闭VS代码。这实际上解决了错误。

Consider using this plugin, as it also supports using audio for web, as opposite to other plugins out there. Hence the number of likes and popularity amongst other audio plugins.

考虑使用这个插件,因为它也支持将音频用于Web,这与其他插件相反。因此,在其他音频插件中,点赞的数量和受欢迎程度都很高。

No implementation found for method play on channel bz.rxla.flutter/audio) Any Idea?

在频道bz.rxla.fltter/音频上没有找到方法播放的实现)有什么想法吗?

there is no sound. I tried it from my side.

没有声音。我试着从我这边。

February 2020 and still no support from Flutter itself. All nice they publish an exotic 'widget of the week' but this is far too basic to not be standard in the library.

2020年2月,仍然没有得到Ffltter本身的支持。他们发布了一个充满异国情调的“本周小工具”,这很好,但这太基本了,不能不成为图书馆的标准。

Do we really need a third party plugin to do something as basic as playing an audio clip?!?

我们真的需要一个第三方插件来做一些像播放音频剪辑这样基本的事情吗?

what should we do if we want to stop this audio?

如果我们想停止这个音频,我们应该怎么做?

@DK250 It perfectly works with any sophisticated folder structure like: assets/sounds/voice/.... You should edit your answer.

@DK250它可以完美地处理任何复杂的文件夹结构,如:Assets/Sound/Voice/...您应该编辑您的答案。

OP asked for mp3, does this plugin play that?

OP要求mp3,这个插件可以播放吗?

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.

没关系,我意识到这一事实碰巧适用于Android上的一些音频文件,并不意味着该插件支持音频播放。我费了好大劲才发现这个插件无法在iOS上播放音频。也没有计划让它工作,因为这不是视频播放器插件的目的。社区中建议的方法是改用@ryanheise的Just_Audio。

@iKeepChangingName Yes, just_audio does play mp3 and it works well.

@iKeepChangingName是的,Just_Audio确实可以播放mp3,并且运行良好。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com