如何在flutter web上播放本地mp3



我尝试了很多软件包,但没有人能从本地文件播放mp3文件。。。

用户可以从系统获取文件

_myFile = await FilePickerCross.importFromStorage(
type: FileTypeCross.audio,  
);

那么,我该如何在flutter网页上播放呢?

通常崩溃:

Error: NotSupportedError: Failed to load because no supported source was found.
at Object.createErrorWithStack (http://localhost:62567/dart_sdk.js:4352:12)
at Object._rethrow (http://localhost:62567/dart_sdk.js:38191:16)
at async._AsyncCallbackEntry.new.callback (http://localhost:62567/dart_sdk.js:38185:13)
at Object._microtaskLoop (http://localhost:62567/dart_sdk.js:38017:13)
at _startMicrotaskLoop (http://localhost:62567/dart_sdk.js:38023:13)
at http://localhost:62567/dart_sdk.js:33520:9

像这样https://github.com/florent37/Flutter-AssetsAudioPlayer/issues/383

那么有什么方法可以在flutterweb上播放本地mp3文件吗?

您可以使用audioplayers包。

要播放本地文件中的音频:

AudioPlayer audioPlayer = AudioPlayer();      
playLocal() async {
int result = await audioPlayer.play(localPath, isLocal: true);
}

有关详细信息,请查看包装文档:

https://pub.dev/packages/audioplayers

您可以在下面复制粘贴运行完整代码
下面的演示代码已经在flutter web上进行了很好的测试
您可以使用包https://pub.dev/packages/soundpool并调用_soundpool.loadAndPlayUint8List(_myFile.toUint8List());
代码片段

Soundpool _soundpool;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
_soundpool = Soundpool();

...
FilePickerCross _myFile = await FilePickerCross.importFromStorage(
type: FileTypeCross.audio,
);
_soundpool.loadAndPlayUint8List(_myFile.toUint8List()); 

全代码

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:file_picker_cross/file_picker_cross.dart';
import 'package:soundpool/soundpool.dart';
Soundpool _soundpool;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
_soundpool = Soundpool();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() async {
FilePickerCross _myFile = await FilePickerCross.importFromStorage(
type: FileTypeCross.audio,
);
_soundpool.loadAndPlayUint8List(_myFile.toUint8List());
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

相关内容

  • 没有找到相关文章

最新更新