React Native中如何向OpenAI Whisper API发送本地音频文件?
React Native中处理本地音频文件调用OpenAI Whisper-1转录的解决方案
核心问题说明
OpenAI Whisper API的file参数需要接收Buffer、Blob或File类型的文件内容,而非本地文件路径字符串。在React Native中,你需要先读取本地文件内容,转换为SDK可接受的格式后再发起请求。
解决方案步骤
1. 安装依赖
首先安装文件处理库及必要工具包:
# 用于读取React Native本地文件 npm install react-native-fs # 用于在React Native中使用Buffer npm install buffer
2. 完整代码实现(Buffer方案)
以下是适配后的代码,通过读取本地文件为Buffer并传递给OpenAI SDK:
import RNFS from 'react-native-fs'; import { Buffer } from 'buffer'; import { Configuration, OpenAI } from "openai"; export const getCompletion5 = async (key) => { const configuration = new Configuration({ apiKey: key }); const openai = new OpenAI(configuration); // 移除file://前缀,react-native-fs需要纯本地路径 const localFilePath = "/data/user/0/com.asd.xyz/cache/sound.mp4"; try { // 读取文件内容为base64格式 const fileBase64 = await RNFS.readFile(localFilePath, 'base64'); // 将base64转换为Buffer,适配OpenAI SDK要求 const audioFile = Buffer.from(fileBase64, 'base64'); // 发起转录请求,必须指定filename参数以识别文件类型 const transcription = await openai.audio.transcriptions.create({ file: audioFile, model: "whisper-1", filename: "sound.mp4" }); console.log(transcription.text); return transcription.text; } catch (error) { console.error("转录请求失败:", error); throw error; // 抛出错误供上层逻辑处理 } }
3. 替代方案(Blob/File类型)
若倾向使用Blob/File格式,可使用rn-fetch-blob库实现:
npm install rn-fetch-blob
import RNFetchBlob from 'rn-fetch-blob'; import { Configuration, OpenAI } from "openai"; export const getCompletion5 = async (key) => { const configuration = new Configuration({ apiKey: key }); const openai = new OpenAI(configuration); const filePath = "file:///data/user/0/com.asd.xyz/cache/sound.mp4"; try { // 读取文件为Blob对象 const blob = await RNFetchBlob.fs.readFile(filePath, 'blob'); // 模拟浏览器File对象,指定文件名和MIME类型 const audioFile = new File([blob], "sound.mp4", { type: "audio/mp4" }); const transcription = await openai.audio.transcriptions.create({ file: audioFile, model: "whisper-1", }); console.log(transcription.text); return transcription.text; } catch (error) { console.error("转录请求失败:", error); throw error; } }
4. Android权限配置
确保应用拥有读取缓存目录的权限,在AndroidManifest.xml中添加:
<!-- Android 12及以下 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- Android 13+ --> <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
关键注意事项
- 必须指定
filename参数:OpenAI需要通过文件名识别音频格式,否则会返回格式错误。 - 路径处理:React Native文件库通常不识别
file://前缀,需移除后使用纯本地路径。 - 异常处理:保留错误抛出逻辑,方便上层业务处理失败场景。
内容的提问来源于stack exchange,提问作者Nemesis
相关产品推荐
相关产品推荐

