Speech emotion recognition is a key technology in the field of artificial intelligence, capable of identifying emotional states in speech. It is widely used in market research and user sentiment analysis. Baidu offers a comprehensive speech emotion recognition API that analyzes uploaded audio data to determine emotions.
This article explains how to call Baidu’s speech emotion recognition API using PHP, with a complete code example to enable quick implementation.
The following example uses PHP’s curl library to send an HTTP POST request to Baidu’s speech emotion recognition API:
<?php // Define API URL $url = 'https://aidemo.baidu.com/api/emotion/v1/audio'; // Set request headers $headers = array( 'Content-Type: application/json;charset=UTF-8', ); // Request parameters $data = array( 'format' => 'pcm', 'token' => 'YOUR_TOKEN', 'cuid' => 'YOUR_CUID', 'rate' => 16000, 'channel' => 1, 'speech' => base64_encode(file_get_contents('YOUR_AUDIO_FILE')), ); // Initialize 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)); // Execute request $result = curl_exec($ch); curl_close($ch); // Parse response if ($result) { $result = json_decode($result, true); if ($result['err_no'] == 0) { // Request successful $emotion = $result['result']['emotion']; echo "Emotion recognition result: $emotion"; } else { // Request failed, display error message $err_msg = $result['err_msg']; echo "Request failed: $err_msg"; } } else { echo "Request failed"; } ?>
Code explanation: First, define the API endpoint and request headers. In the request parameters, replace YOUR_TOKEN and YOUR_CUID with your token and device ID, and replace YOUR_AUDIO_FILE with the path to the audio file you want to analyze. The request is sent in JSON format, and the response is parsed to directly retrieve the emotion recognition result.
This article introduces the complete process of calling Baidu’s speech emotion recognition API using PHP, including account setup, environment configuration, and code implementation. By using this API, you can quickly realize speech emotion analysis functionality, providing smarter user experiences and better data support for businesses.