我正在尝试播放一个自定义的mp3声音我已经将资产文件夹放入app文件夹中,就像你对字体或图像文件所做的那样,但后来我真的不知道如何继续 . 我想我可能需要将音频文件注册到pubspec.yaml,但是如何?
我该怎么玩呢?
我已经检查了这两个答案:How to play a custom sound in Flutter?
Flutter - Play custom sounds updated?
但是第一个太旧了,第二个使用URL作为声音路径: const kUrl2 = "http://www.rxlabz.com/labz/audio.mp3";
而我喜欢播放的声音是在应用中,而不是在线 . 那么......我怎么能这样做?
这是我的当前代码,如您所见,只有一个浮动按钮 . 我需要在点上启动声音我在代码中说明了它 .
但是视觉工作室以红色突出显示各个部分: await :它表示等待无法识别 . audioPlugin.play :是说它也未被承认
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());
Directory tempDir = await getTemporaryDirectory();
File tempFile = new File('${tempDir.path}/demo.mp3');
await tempFile.writeAsBytes(bytes, flush: true);
AudioPlayer audioPlugin = new AudioPlayer();
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void _incrementCounter() {
setState(() {
print("Button Pressed");
///
///
///
/// Here I Need To start Playing the Sound
///
///
///
///
audioPlugin.play(tempFile.uri.toString(), isLocal: true);
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
1 回答
它不漂亮,但......
将mp3文件添加到assets文件夹并将其添加到
pubspec.yaml
,如this .使用
rootBundle.load(asset)
将资产作为二进制数据加载使用
path_provider
获取应用程序的临时文件夹位置使用常规
dart:io
在tempDir
中打开文件(可能使用资产名称)并将bytes
写入其中 .从
file:///folderPath/fileName
形式的临时文件名形成file
URL将此传递给audioplayer,将
isLocal
设置为true(在iOS上需要) .