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

如何基于MP3LameEncoder.js将Blob URL转Base64并发送至服务器?

解决方案:将Audio Blob URL转换为Base64或直接上传至服务器

优先推荐:直接上传Blob(更高效)

转Base64会额外增加约33%的文件体积,所以如果服务器支持直接接收Blob,优先用这个方法:

  • 先获取你的audio元素,通过fetch请求Blob URL拿到原始Blob对象
  • 用FormData包装Blob,再通过fetch或XMLHttpRequest发送到服务器

代码示例:

const audioElement = document.getElementById('audio');

// 获取Blob对象
fetch(audioElement.src)
  .then(response => response.blob())
  .then(blob => {
    // 创建FormData用于上传
    const formData = new FormData();
    // 把Blob添加到FormData,命名可根据服务器要求调整
    formData.append('audioFile', blob, 'audio.mp3');
    
    // 发送到服务器
    fetch('/your-server-endpoint', {
      method: 'POST',
      body: formData
    })
    .then(serverResponse => {
      if (serverResponse.ok) {
        console.log('音频上传成功!');
        // 继续你的多步骤流程
      } else {
        console.error('上传失败,请检查服务器配置');
      }
    })
    .catch(error => {
      console.error('请求出错:', error);
    });
  })
  .catch(error => {
    console.error('获取Blob失败:', error);
  });

转为Base64后上传(如果服务器要求)

如果你的服务器必须接收Base64格式的音频数据,可以用FileReader来转换:

  • 同样先获取Blob对象,然后用FileReader读取为Data URL
  • 提取Data URL中data:audio/mpeg;base64,之后的部分,就是纯Base64字符串

代码示例:

const audioElement = document.getElementById('audio');

fetch(audioElement.src)
  .then(response => response.blob())
  .then(blob => {
    const reader = new FileReader();
    reader.onload = function(e) {
      // 获取完整的Data URL
      const dataUrl = e.target.result;
      // 提取Base64部分
      const base64String = dataUrl.split(',')[1];
      
      // 发送Base64到服务器,可根据需求调整发送格式
      fetch('/your-server-endpoint', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          audioBase64: base64String,
          fileName: 'audio.mp3'
        })
      })
      .then(serverResponse => {
        if (serverResponse.ok) {
          console.log('Base64音频上传成功!');
        } else {
          console.error('上传失败');
        }
      })
      .catch(error => {
        console.error('请求出错:', error);
      });
    };
    // 以Data URL格式读取Blob
    reader.readAsDataURL(blob);
  })
  .catch(error => {
    console.error('处理Blob失败:', error);
  });

额外提示

  • Blob URL是临时的,页面刷新或关闭后就会失效,务必在当前会话内完成转换/上传
  • 如果你是用MP3LameEncoder.js直接生成的Blob,其实可以跳过audio元素的src,直接使用生成的Blob对象,能节省一次请求步骤

内容的提问来源于stack exchange,提问作者Travis Johnston

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:52:29