Android调用Whisper API持续返回400 Invalid File Format错误求助
解决Android调用Whisper API返回"invalid file format" 400错误的方案
核心问题分析
- 录制格式不兼容:你使用的
MediaRecorder.OutputFormat.DEFAULT和AudioEncoder.DEFAULT在Android设备上并非标准WAV配置,实际生成的文件可能是3GP容器+AMR编码(即使后缀是.wav),不符合Whisper要求的PCM编码WAV格式。 - 请求头错误:手动设置
Content-Type: multipart/form-data会覆盖OkHttp自动生成的带boundary参数的正确头,导致服务器无法解析多部分表单数据。
修改后的代码
1. 修正音频录制配置
private void startRecording() { fileName = getExternalCacheDir().getAbsolutePath() + "/recording.wav"; recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 明确指定WAV输出格式 recorder.setOutputFormat(MediaRecorder.OutputFormat.WAVE); recorder.setOutputFile(fileName); // 使用Whisper兼容的PCM 16位编码器 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.PCM_16BIT); // 设置Whisper推荐的16kHz单声道采样率 recorder.setAudioSamplingRate(16000); recorder.setAudioChannels(1); try { recorder.prepare(); } catch (IOException e) { e.printStackTrace(); } recorder.start(); }
2. 修正API请求配置
private void stopRecording() { recorder.stop(); recorder.release(); recorder = null; OkHttpClient client = new OkHttpClient(); File file = new File(fileName); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("audio/wav"), file)) .addFormDataPart("model", "whisper-1") .build(); Request request = new Request.Builder() .url("https://api.openai.com/v1/audio/transcriptions") .post(requestBody) .header("Authorization", "Bearer sk-QAym*******gUIRdxXGq") // 移除手动设置的Content-Type,MultipartBody会自动生成带boundary的正确头 .build(); client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException { if (!response.isSuccessful()) { System.out.println("Unexpected code " + response); } System.out.println(response.body().string()); } }); }
关键说明
- 录制配置必须明确指定
WAVE输出格式和PCM_16BIT编码器,同时匹配Whisper要求的16kHz单声道参数,确保生成标准兼容的WAV文件。 - 无需手动设置
Content-Type头,OkHttp的MultipartBody会自动生成包含boundary的正确请求头,避免服务器解析失败。
内容的提问来源于stack exchange,提问作者Manoj ahirwar
相关产品推荐
相关产品推荐

