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

Flutter Web使用flutter_sound录音后如何将Blob路径转为Uint8List上传?

Flutter中flutter_sound录制音频Blob路径转Uint8List方案

针对你用flutter_sound录制后得到的Blob格式路径(如blob:http://localhost:64911/e9c17898-7698-4fd5-8739-be1d8b53153c),可按以下步骤转换为Uint8List用于服务器上传:

1. 依赖导入(仅Web平台)

由于Blob URL是浏览器环境的产物,需导入dart:html处理,同时添加条件导入避免其他平台编译报错:

import 'dart:convert';
import 'dart:typed_data';
// 仅在Web平台生效
import 'dart:html' as html;

2. 编写转换函数

通过浏览器的HTTP请求和FileReader API读取Blob内容并转为Uint8List:

Future<Uint8List?> blobUrlToUint8List(String blobUrl) async {
  try {
    // 发起请求获取Blob资源
    final request = html.HttpRequest();
    await request.open('GET', blobUrl);
    request.responseType = 'blob';
    await request.send();

    // 将Blob转为Uint8List
    final blob = request.response as html.Blob;
    final reader = html.FileReader();
    reader.readAsArrayBuffer(blob);
    await reader.onLoad.first;

    return reader.result as Uint8List;
  } catch (e) {
    print('Blob转Uint8List失败: $e');
    return null;
  }
}

3. 调用转换并上传

拿到录制后的Blob URL后,调用转换函数,再将得到的Uint8List上传至服务器:

// 假设stopRecording返回的路径为blobUrl
final blobUrl = 'blob:http://localhost:64911/e9c17898-7698-4fd5-8739-be1d8b53153c';
final uint8List = await blobUrlToUint8List(blobUrl);

if (uint8List != null) {
  // 此处编写服务器上传逻辑,示例用http包发送multipart请求
  // final request = http.MultipartRequest('POST', Uri.parse('你的上传接口地址'));
  // request.files.add(http.MultipartFile.fromBytes('audio', uint8List, filename: 'recording.wav'));
  // final response = await request.send();
}

注意事项

  • 上述方案仅适用于Flutter Web平台;Android/iOS等原生平台中,flutter_sound返回的是本地文件路径,直接用dart:io读取即可:Uint8List.fromList(await File(path).readAsBytes())
  • Blob URL仅在当前会话有效,页面刷新后会失效,需及时处理
  • 确保Blob资源同源,避免跨域请求被浏览器拦截

内容的提问来源于stack exchange,提问作者yalda mohasseli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:07:40