You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web:如何将flutter_sound录制的Blob URL转为Uint8List?

Flutter Web:将flutter_sound生成的Blob URL转换为Uint8List

要在Flutter Web端把flutter_sound录制得到的Blob URL转为可上传的Uint8List,你需要借助浏览器原生API(通过dart:html包)实现,具体步骤如下:

1. 导入必要依赖

在代码中导入Web端专用的dart:html包和Uint8List相关的dart:typed_data,若为跨平台项目,还需导入跨平台判断工具:

import 'dart:html' as html;
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show kIsWeb;

2. 实现转换函数

编写异步函数完成Blob URL到Uint8List的转换:

Future<Uint8List> convertBlobUrlToUint8List(String blobUrl) async {
  // 发送请求获取Blob资源
  final html.HttpRequest request = await html.HttpRequest.request(
    blobUrl,
    responseType: 'blob',
  );

  // 从响应中提取Blob对象
  final html.Blob blob = request.response as html.Blob;

  // 使用FileReader读取Blob为ArrayBuffer
  final html.FileReader reader = html.FileReader();
  reader.readAsArrayBuffer(blob);

  // 等待读取完成
  await reader.onLoad.first;

  // 将ArrayBuffer转换为Uint8List
  return Uint8List.view(reader.result as ByteBuffer);
}

3. 调用转换函数并上传

在业务逻辑中调用上述函数处理flutter_sound返回的Blob URL,之后即可将Uint8List上传至Firestore等平台:

// 假设这是flutter_sound录制完成后返回的Blob URL
final String recordedBlobUrl = 'blob:http://localhost:54779/f1b68f68-8007-4168-abd3-3de5ec8cabbe';

if (kIsWeb) {
  try {
    Uint8List audioBytes = await convertBlobUrlToUint8List(recordedBlobUrl);
    // 编写上传逻辑,例如存入Firestore
    // FirebaseFirestore.instance.collection('audios').add({'audio_data': audioBytes});
  } catch (e) {
    print('转换失败: $e');
  }
}

注意事项

  • 该代码仅适用于Flutter Web环境,跨平台项目务必用kIsWeb做环境判断,避免移动端编译报错。
  • 若Blob URL为跨域资源,需目标服务器配置CORS允许访问,否则会出现请求失败。

内容的提问来源于stack exchange,提问作者Ahmed Galal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:17:00