Google语音API“请求中的采样率”与FLAC头文件“不匹配”


Google Speech API "Sample rate in request does not match FLAC header"

我正在尝试将mp4视频剪辑转换为FLAC音频文件,然后让google语音从视频中吐出单词,以便我可以检测是否说了特定的单词。

我有一切工作,除了我从语音API得到一个错误:

{
  "error": {
    "code": 400,
    "message": "Sample rate in request does not match FLAC header.",
    "status": "INVALID_ARGUMENT"
  }
}

我正在使用FFMPEG,以便将mp4转换为FLAC文件。我在命令中指定FLAC文件为16位,但是当我右键单击FLAC文件时,Windows告诉我它是302kbps。

下面是我的PHP代码:
// convert mp4 video to 16 bit flac audio file
$cmd = 'C:/wamp/www/ffmpeg/bin/ffmpeg.exe -i C:/wamp/www/test.mp4 -c:a flac -sample_fmt s16 C:/wamp/www/test.flac';
exec($cmd, $output);
// convert flac to text so we can detect if certain words were said
$data = array(
    "config" => array(
        "encoding" => "FLAC",
        "sampleRate" => 16000,
        "languageCode" => "en-US"
    ),
    "audio" => array(
        "content" => base64_encode(file_get_contents("test.flac")),
    )
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=MY_API_KEY');
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);

通过在我的FFMPEG命令中非常具体地修复了它:

$cmd = 'C:/wamp/www/ffmpeg/bin/ffmpeg.exe -i C:/wamp/www/test.mp4 -acodec flac -bits_per_raw_sample 16 -ar 44100 -ac 1 C:/wamp/www/test.flac';

kjdion84的答案效果很好,为了找出根本原因,我又玩了一会儿。

根据这个答案,所有编码只支持1声道(单声道)音频

我正在用这个命令创建FLAC文件:

ffmpeg -i test.mp3 test.flac

请求中的采样率与FLAC标头不匹配

但是添加-ac 1(将音频通道数量设置为1)修复了此问题。

ffmpeg -i test.mp3 -ac 1 test.flac

这是我完整的Node.js代码

const Speech = require('@google-cloud/speech');
const projectId = 'EnterProjectIdGeneratedByGoogle';
const speechClient = Speech({
    projectId: projectId
});
// The name of the audio file to transcribe
var fileName = '/home/user/Documents/test/test.flac';

// The audio file's encoding and sample rate
const options = {
    encoding: 'FLAC',
    sampleRate: 44100
};
// Detects speech in the audio file
speechClient.recognize(fileName, options)
    .then((results) => {
        const transcription = results[0];
        console.log(`Transcription: ${transcription}`);
    }, function(err) {
        console.log(err);
    });

采样率可以是16000或44100或其他有效采样率,编码可以是FLAC或LINEAR16。云演讲文档