首先获取百度AI平台的API Key和Secret Key,然后通过cURL请求获取Access Token,接着将音频文件转为base64编码并发送至百度ASR接口进行识别,最后解析返回结果。完整流程包括权限申请、Token获取、音频上传与识别,需注意音频格式、大小限制及Token缓存。

要使用PHP调用百度语音识别API实现语音转文字,关键在于获取Access Token、上传音频文件并发送请求到百度ASR接口。整个过程需要遵循百度AI开放平台的规范,下面一步步说明如何实现。
在调用百度语音识别API前,必须先注册百度AI开放平台账号,并创建应用以获取凭证信息。
进入 百度AI开放平台(https://ai.baidu.com),选择“语音识别”服务,创建应用后会得到:
通过这两个密钥可以获取Access Token,这是调用API的必要参数。
立即学习“PHP免费学习笔记(深入)”;
Access Token是调用百度API的身份令牌,有效期一般为30天,可通过以下接口获取:
https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【API Key】&client_secret=【Secret Key】使用PHP的cURL发送请求获取Token:
function getAccessToken($apiKey, $secretKey) {
$url = "https://aip.baidubce.com/oauth/2.0/token";
$post_data = [
'grant_type' => 'client_credentials',
'client_id' => $apiKey,
'client_secret' => $secretKey
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
return $result['access_token'];
}
百度语音识别接口支持多种格式(如pcm、wav、amr等),采样率需为8000或16000Hz。以下是上传音频并识别的示例代码:
function speechToText($audioFilePath, $format = 'wav', $rate = 16000, $token) {
$speech = file_get_contents($audioFilePath);
$len = filesize($audioFilePath);
$speech = base64_encode($speech);
$data = [
"format" => $format,
"rate" => $rate,
"channel" => 1,
"cuid" => "your_unique_id", // 可以是设备ID或随机字符串
"token" => $token,
"speech" => $speech,
"len" => $len
];
$json_data = json_encode($data);
$url = "https://vop.baidubce.com/v1/recognition/simple";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data)
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
调用方式:
$apiKey = '你的API Key';
$secretKey = '你的Secret Key';
$token = getAccessToken($apiKey, $secretKey);
$result = speechToText('test.wav', 'wav', 16000, $token);
if (isset($result['result'])) {
echo "识别结果:" . $result['result'][0];
} else {
echo "识别失败:" . $result['err_msg'];
}
实际使用中需要注意以下几点:
基本上就这些。只要拿到Token,正确封装音频数据,就能顺利实现语音转文字功能。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号