如何将应用程序文件中的语音文件(mpeg)分享给其他应用程序(如 whatsapp)

How can I share voice file(mpeg) which in app files to other app(like whatsapp) in flutter

我尝试使用 flutter share 2.0.1 插件来共享语音文件,但它没有用(没有这样的文件)。你能解决这个问题吗?或者我如何将语音文件共享到其他应用程序?这是我的代码和错误截图。


E/flutter (31567): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: PlatformException(assets/voices/pırt.mpeg (No such file or directory), null, null, null)
E/flutter (31567): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:597:7)
E/flutter (31567): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:158:18)

IconButton(
              icon: Icon(Icons.send),
              color: Colors.black,
              iconSize: 35,
              onPressed: () {
                try{
                  Share.shareFiles(["assets/voices/pırt.mpeg"],text: "Share");
                }
                catch(ex){
                  print(ex);
                }
              },
            ),

如错误所述,assets/voices/pırt.mpeg 不是 OS 上文件的有效路径。这是一种资产,打包到您的应用程序中。如果你想分享资产,你需要先把它们做成一个文件在设备上。

您需要添加 path_provider 依赖项:

dependencies:
  path_provider: ^2.0.1

然后,创建一个新的 File 并将资产中的数据写入 File:

//Get directory and make a file object
final Directory dir = await getTemporaryDirectory();
final File file = File(dir.path + '/mpeg_data');

//Get data from assets
ByteData data = await rootBundle.load('assets/voices/pırt.mpeg');

//Write actual data
await file.writeAsBytes(data.buffer.asUint8List());

这一切都应该在您共享文件之前完成。然后在分享文件的时候,使用你创建的文件对象的路径:

//Get directory and make a file object
final Directory dir = await getTemporaryDirectory();
final File file = File(dir.path);

//Get data from assets
ByteData data = await rootBundle.load('assets/voices/pırt.mpeg');

//Write actual data
await file.writeAsBytes(data.buffer.asUint8List());

try{
  Share.shareFiles([file.path],text: "Share");
}
catch(ex){
  print(ex);
}