【发布时间】:2019-01-24 20:39:14
【问题描述】:
我正在尝试播放我在资产文件夹中放入应用程序文件夹的自定义 mp3 声音,就像您对字体或图像文件所做的那样,但我真的不知道如何继续。我想我可能需要将音频文件注册到 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";,而我喜欢播放的声音是在应用程序中,而不是在线。那么...我该怎么做呢?
这是我当前的代码,如您所见,只有一个浮动按钮。 而且我需要在我在代码中声明的那一点开始声音。
但是visual studio用红色下划线的各个部分: await:表示 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),
),
);
}
}
【问题讨论】:
-
pub.dev/packages/audioplayers 使用这个包并查看包 url 上给出的示例。