本文目录导读:

我来详细介绍PHP集成语音识别API的方法:
主流语音识别API选择
百度语音识别
<?php
// 使用百度语音识别API
require_once 'AipSpeech.php';
// 配置AppID、API Key、Secret Key
const APP_ID = '你的AppID';
const API_KEY = '你的API Key';
const SECRET_KEY = '你的Secret Key';
$client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
// 读取音频文件
$audio = file_get_contents('/path/to/audio.pcm');
// 调用语音识别
$result = $client->asr($audio, 'pcm', 16000, [
'dev_pid' => 1536, // 普通话(支持简单英文)
]);
print_r($result);
?>
阿里云语音识别
<?php
// 使用阿里云语音识别
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
// 配置AK
AlibabaCloud::accessKeyClient('your-access-key-id', 'your-access-key-secret')
->regionId('cn-shanghai')
->asDefaultClient();
try {
$result = AlibabaCloud::nlsFiletrans()
->v20180817()
->submitTask()
->withFileUrl('https://your-bucket.oss-cn-shanghai.aliyuncs.com/audio.wav')
->withCallbackUrl('http://your-callback-url.com/callback')
->withAppkey('your-appkey')
->request();
print_r($result->toArray());
} catch (ClientException $e) {
echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
echo $e->getErrorMessage() . PHP_EOL;
}
?>
腾讯云语音识别
<?php
// 使用腾讯云语音识别
require_once './vendor/autoload.php';
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Asr\V20190614\AsrClient;
use TencentCloud\Asr\V20190614\Models\CreateRecTaskRequest;
$cred = new Credential("your-secret-id", "your-secret-key");
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("asr.tencentcloudapi.com");
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new AsrClient($cred, "ap-guangzhou", $clientProfile);
$req = new CreateRecTaskRequest();
$params = array(
"EngineModelType" => "16k_0",
"ChannelNum" => 1,
"ResTextFormat" => 0,
"SourceType" => 0,
"Url" => "https://your-audio-url.com/audio.wav"
);
$req->fromJsonString(json_encode($params));
$resp = $client->CreateRecTask($req);
print_r(json_decode($resp->toJsonString(), true));
?>
通用PHP语音识别类
<?php
class SpeechRecognition {
private $apiKey;
private $apiUrl;
public function __construct($apiKey, $apiUrl) {
$this->apiKey = $apiKey;
$this->apiUrl = $apiUrl;
}
/**
* 识别音频文件
* @param string $audioFilePath 音频文件路径
* @param string $format 音频格式
* @return array
*/
public function recognize($audioFilePath, $format = 'wav') {
if (!file_exists($audioFilePath)) {
return ['error' => '音频文件不存在'];
}
// 读取音频文件
$audioData = file_get_contents($audioFilePath);
// 转换为base64
$base64Audio = base64_encode($audioData);
// 发送请求
$response = $this->sendRequest($base64Audio, $format);
return json_decode($response, true);
}
/**
* 发送请求到语音识别API
*/
private function sendRequest($audioData, $format) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->apiKey
]);
$requestData = [
'audio' => [
'content' => $audioData,
'format' => $format
],
'config' => [
'language' => 'zh-CN', // 语言
'sample_rate' => 16000 // 采样率
]
];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
return json_encode(['error' => 'API请求失败', 'http_code' => $httpCode]);
}
curl_close($ch);
return $response;
}
/**
* 实时语音识别(WebSocket)
*/
public function realTimeRecognize($audioStream, $callback) {
// WebSocket实现实时识别
// 这里需要根据具体的API实现
throw new Exception('实时识别需要具体API支持');
}
}
// 使用示例
$recognizer = new SpeechRecognition(
'your-api-key',
'https://api.example.com/v1/speech/recognize'
);
$result = $recognizer->recognize('/path/to/audio.wav');
if (!isset($result['error'])) {
echo "识别结果: " . $result['text'];
} else {
echo "错误: " . $result['error'];
}
?>
音频预处理
<?php
/**
* 音频预处理类
*/
class AudioPreprocessor {
/**
* 转换音频格式
*/
public static function convertFormat($inputFile, $outputFile, $targetFormat = 'wav') {
$command = "ffmpeg -i {$inputFile} -acodec pcm_s16le -ar 16000 -ac 1 {$outputFile}";
exec($command, $output, $returnCode);
return $returnCode === 0;
}
/**
* 剪切音频
*/
public static function trimAudio($inputFile, $outputFile, $startTime, $duration) {
$command = "ffmpeg -i {$inputFile} -ss {$startTime} -t {$duration} -c copy {$outputFile}";
exec($command, $output, $returnCode);
return $returnCode === 0;
}
/**
* 检测音频是否有效
*/
public static function validateAudio($audioFile) {
$command = "ffprobe -v quiet -print_format json -show_format " . escapeshellarg($audioFile);
exec($command, $output, $returnCode);
if ($returnCode !== 0) {
return false;
}
$info = json_decode(implode('', $output), true);
$format = $info['format'];
// 检查格式和大小
if (!isset($format['duration']) || $format['duration'] > 60) {
return false; // 音频超过60秒
}
if (!isset($format['size']) || $format['size'] > 10 * 1024 * 1024) {
return false; // 文件超过10MB
}
return true;
}
}
?>
完整集成示例
<?php
// index.php - 语音识别示例页面
require_once 'SpeechRecognition.php';
require_once 'AudioPreprocessor.php';
// 处理上传的音频文件
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['audio'])) {
$uploadDir = 'uploads/';
$convertedDir = 'converted/';
// 创建目录
if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);
if (!file_exists($convertedDir)) mkdir($convertedDir, 0777, true);
$uploadFile = $uploadDir . basename($_FILES['audio']['name']);
$convertedFile = $convertedDir . 'converted_' . time() . '.wav';
// 上传文件
if (move_uploaded_file($_FILES['audio']['tmp_name'], $uploadFile)) {
// 预处理音频
if (AudioPreprocessor::validateAudio($uploadFile)) {
// 转换格式
AudioPreprocessor::convertFormat($uploadFile, $convertedFile, 'wav');
// 初始化识别器
$recognizer = new SpeechRecognition(
'your-api-key',
'https://api.speech-recognition.com/v1/recognize'
);
// 执行识别
$result = $recognizer->recognize($convertedFile);
// 显示结果
if (isset($result['text'])) {
echo "识别结果: " . htmlspecialchars($result['text']);
} else {
echo "识别失败: " . json_encode($result);
}
// 清理临时文件
unlink($uploadFile);
unlink($convertedFile);
} else {
echo "音频文件无效";
}
} else {
echo "文件上传失败";
}
}
?>
<!DOCTYPE html>
<html>
<head>语音识别演示</title>
</head>
<body>
<h1>语音识别演示</h1>
<form method="post" enctype="multipart/form-data">
<input type="file" name="audio" accept="audio/*" required>
<button type="submit">识别语音</button>
</form>
<!-- 或使用麦克风在线录音 -->
<button id="startBtn">开始录音</button>
<button id="stopBtn" disabled>停止录音</button>
<script>
let mediaRecorder;
let audioChunks = [];
document.getElementById('startBtn').onclick = async function() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.ondataavailable = event => {
audioChunks.push(event.data);
};
mediaRecorder.onstop = function() {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const formData = new FormData();
formData.append('audio', audioBlob, 'recording.wav');
fetch('', {
method: 'POST',
body: formData
}).then(response => response.text())
.then(result => alert(result));
};
mediaRecorder.start();
document.getElementById('startBtn').disabled = true;
document.getElementById('stopBtn').disabled = false;
};
document.getElementById('stopBtn').onclick = function() {
mediaRecorder.stop();
document.getElementById('startBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
};
</script>
</body>
</html>
依赖安装
# 安装必要的PHP扩展 sudo apt-get install php-curl php-json # 安装FFmpeg用于音频处理 sudo apt-get install ffmpeg # 使用Composer安装SDK(以阿里云为例) composer require alibabacloud/client # 或其他云服务商SDK composer require qcloud/cos-sdk-v5
注意事项
- API Key安全:不要在代码中硬编码,使用环境变量
- 音频格式:通常需要16kHz、16bit、单声道PCM或WAV格式
- 文件大小限制:多数API有文件大小限制(通常10-20MB)
- 错误处理:完善的错误处理和重试机制
- 成本控制:注意API调用次数限制和费用
建议优先选择国内云服务商的API,延迟更小,支持更全面。