語音情感識別是人工智能領域的重要技術之一,能夠識別語音中的情緒狀態,廣泛應用於市場調研和用戶情感分析。百度提供了功能完善的語音情感識別接口,可以對上傳的語音數據進行情緒判斷。
本文將介紹如何用PHP調用百度語音情感識別接口,並附帶完整代碼示例,方便快速實現該功能。
下面示例使用PHP的curl庫向百度語音情感識別接口發送HTTP POST請求:
<?php
// 定義接口URL
$url = 'https://aidemo.baidu.com/api/emotion/v1/audio';
// 設置請求頭
$headers = array(
'Content-Type: application/json;charset=UTF-8',
);
// 請求參數
$data = array(
'format' => 'pcm',
'token' => 'YOUR_TOKEN',
'cuid' => 'YOUR_CUID',
'rate' => 16000,
'channel' => 1,
'speech' => base64_encode(file_get_contents('YOUR_AUDIO_FILE')),
);
// 初始化curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
// 執行請求$result = curl_exec($ch);
curl_close($ch);
// 解析返回結果if ($result) {
$result = json_decode($result, true);
if ($result['err_no'] == 0) {
// 請求成功$emotion = $result['result']['emotion'];
echo "情感識別結果:$emotion";
} else {
// 請求失敗,輸出錯誤信息$err_msg = $result['err_msg'];
echo "請求失敗:$err_msg";
}
} else {
echo "請求失敗";
}
?>代碼說明:首先定義接口地址及請求頭。請求參數中,需替換YOUR_TOKEN和YOUR_CUID為您申請的token和設備ID, YOUR_AUDIO_FILE替換為需要分析的音頻文件路徑。請求以JSON格式發送,返回結果解析後可直接獲取情感識別結果。
本文介紹了PHP調用百度語音情感識別接口的完整流程,包括賬號准備、環境配置及代碼實現。通過該接口,可以快速實現語音的情緒分析功能,為企業提供更智能的用戶體驗和數據支持。