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

Android调用Whisper API持续返回400 Invalid File Format错误求助

解决Android调用Whisper API返回"invalid file format" 400错误的方案

核心问题分析

  1. 录制格式不兼容:你使用的MediaRecorder.OutputFormat.DEFAULT和AudioEncoder.DEFAULT在Android设备上并非标准WAV配置,实际生成的文件可能是3GP容器+AMR编码(即使后缀是.wav),不符合Whisper要求的PCM编码WAV格式。
  2. 请求头错误:手动设置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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:13:30