Baidu Text-to-Speech API allows you to convert text into speech, which can be widely used in voice interaction, navigation, broadcasting, automotive, and other fields. This article will explain in detail how to integrate Baidu Text-to-Speech API with PHP, helping developers quickly implement speech synthesis features.
Before you start writing PHP code, there are a few preparatory steps you need to complete:
First, register a Baidu developer account, log in to the Baidu AI open platform, create a new application, and enable the Speech Technology Service.
After registration, you need to create an application. The steps are as follows:
Once the application is created, you can find the "App ID" and "API Key" information in the "My Applications" section.
Before writing PHP code, ensure that your PHP environment is properly set up. Follow these steps:
Once the preparations are complete, the next step is to integrate PHP with the Baidu Text-to-Speech API. The steps are as follows:
Before calling the Baidu API, make sure your PHP environment has the CURL and JSON extensions installed. You can install them using the following commands:
sudo apt-get install php-curl sudo apt-get install php-json
Before calling the Baidu Text-to-Speech API, you need to construct the request parameters according to the API documentation. Follow these steps:
Once the request parameters are constructed, use the CURL library to send the API request and parse the returned JSON data.
After calling the API, you need to process the returned data to extract the audio file's binary data and save it locally. Below is an example of how to handle the API response:
$url = 'https://tsn.baidu.com/text2audio'; $text = 'Baidu Text-to-Speech API Integration'; $data = array( 'tex' => base64_encode($text), // Base64 encode the text 'lan' => 'zh', // Language type 'tok' => $access_token, // Access Token 'ctp' => '1', // Client type 'cuid' => '123456' // Client identifier ); $data = http_build_query($data); $url = $url . '?' . $data; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); $result = curl_exec($ch); curl_close($ch); // Parse the returned JSON data into an array $result_arr = json_decode($result, true); // Extract the audio file and save it locally $audio = base64_decode($result_arr['data']['audio']); file_put_contents('audio.mp3', $audio);
With this tutorial, you have learned how to integrate the Baidu Text-to-Speech API with PHP. In actual applications, you may also need to consider code optimization, stress testing, and other factors to ensure the stability of the program under high concurrency.