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

使用Whisper转写音频时遇Invalid URL错误(JS正常TS异常)

解决Whisper本地音频文件转写的Invalid URL错误

错误根源:createFile函数中用fetch读取本地文件路径,Node.js环境下的fetch仅支持HTTP/HTTPS等合法URL,本地文件路径会被判定为无效URL导致报错。此外Node.js无需模拟浏览器的File对象,OpenAI SDK直接支持本地文件流或Buffer作为输入。

修正方案

直接使用Node.js的fs模块读取本地音频文件,传递给Whisper接口即可,无需转成File对象。以下提供两种实现方式:

方式1:使用Buffer读取(适合小文件)

import fs from 'fs/promises';
import path from 'path';

async function sendAudioForTranscription(file_path: string) {
  try {
    // 生成绝对路径避免相对路径问题
    const absolutePath = path.resolve(__dirname, file_path);
    // 读取文件为Buffer
    const audioBuffer = await fs.readFile(absolutePath);
    
    // 提取文件名与MIME类型
    const fileName = path.basename(absolutePath);
    const fileExtension = path.extname(fileName).slice(1).toLowerCase();
    const mimeTypes: Record<string, string> = {
      'mp3': 'audio/mpeg',
      'wav': 'audio/wav',
      'm4a': 'audio/mp4',
      // 按需添加更多音频格式
    };
    const fileType = mimeTypes[fileExtension] || 'application/octet-stream';

    // 将Buffer包装为Blob传递给Whisper
    const response = await openai.createTranscription(
      new Blob([audioBuffer], { type: fileType }) as unknown as File, 
      "whisper-1",
      undefined,
      undefined,
      undefined,
      fileName
    );

    return response.data.text;
  } catch (error) {
    console.error("Error transcribing the audio:", error);
    return null;
  }
}

方式2:使用文件流(适合大文件)

import fs from 'fs';
import path from 'path';

async function sendAudioForTranscription(file_path: string) {
  try {
    const absolutePath = path.resolve(__dirname, file_path);
    const audioStream = fs.createReadStream(absolutePath);
    
    const fileName = path.basename(absolutePath);
    const fileExtension = path.extname(fileName).slice(1).toLowerCase();
    const mimeTypes: Record<string, string> = {
      'mp3': 'audio/mpeg',
      'wav': 'audio/wav',
      'm4a': 'audio/mp4',
    };
    const fileType = mimeTypes[fileExtension] || 'application/octet-stream';

    const response = await openai.createTranscription(
      audioStream, 
      "whisper-1",
      undefined,
      undefined,
      undefined,
      fileName,
      { headers: { 'Content-Type': fileType } }
    );

    return response.data.text;
  } catch (error) {
    console.error("Error transcribing the audio:", error);
    return null;
  }
}

注意事项

  • 确保安装TypeScript的Node.js类型支持:npm install @types/node --save-dev
  • 优先使用绝对路径读取文件,避免因运行目录不同导致的路径错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:43:16