Baidu Speech REST API Demos

repository·master·Indexed 20 days ago

https://github.com/baidu-aip/speech-demo

A collection of demonstration code for Baidu's Speech REST APIs, providing multi-language implementations for Speech Recognition (ASR) and Speech Synthesis (TTS). The repository includes examples in Bash Shell, Java, C, PHP, and Python, covering standard recognition, the Speed Version (极速版), and custom models from the Self-Training Platform.

Tokens
10.9K
Snippets
45
Records
72
Agent score
71%

What's inside baidu-aip-speech-demo

  1. Overview of Baidu Speech REST API Demos

    master

    This repository provides implementation examples for Baidu Speech REST APIs, specifically covering Speech Recognition (ASR) and Speech Synthesis (TTS).

    Because these are REST APIs accessed via HTTP, they are platform-agnostic and can be used with any operating system or programming language capable of making HTTP requests.

    Key Capabilities:

    • Speech Recognition (ASR): Converts audio input to text.
    • Speech Synthesis (TTS): Converts text input to synthesized speech.

    Important Note on CORS: Baidu Speech Synthesis (TTS) interfaces support Cross-Origin Resource Sharing (CORS), allowing for browser-based requests. However, the interface used to obtain the access token does not support CORS. For browser-based TTS examples, refer to the dedicated repository: https://github.com/Baidu-AIP/SPEECH-TTS-CORS.

  2. Core JSON components in org.json

    master

    The org.json package provides a reference implementation for JSON encoding and decoding in Java. The primary classes for handling JSON data are:

    • JSONObject: A map-like object used to parse text from a String or JSONTokener. It allows for manual manipulation of contents and produces JSON-compliant serialized strings.
    • JSONArray: A vector-like object used to parse text from a String or JSONTokener. It allows for manual manipulation of contents and produces JSON-compliant array serialization.
    • JSONTokener: A utility that breaks text into a sequence of individual tokens. It can be initialized using a String, Reader, or InputStream.
    • JSONException: The standard exception type thrown when parsing or manipulating JSON fails.
  3. Run TTS synthesis using tts.sh

    master

    Execute the synthesis script using the following command:

    sh tts.sh

    Interpreting the Results:

    • The synthesized audio is saved to result.mp3.
    • Success: If the HTTP response header contains Content-Type: audio/mp3, the synthesis was successful and you can play result.mp3.
    • Failure: If the HTTP response header contains Content-Type: application/json, an error occurred. Rename result.mp3 to result.txt and open it to view the JSON error message.

    Token Requirements:

    • Ensure your access token's scope includes audio_tts_post. If it does not, you must activate this capability in the Baidu web console.
    • The token expires after the duration specified in expires_in seconds.
  4. Configure audio files and PIDs for ASR testing

    master

    To test different audio files or languages, modify the following variables in the script:

    • FILE: The path to your audio file.
    • FORMAT: The file format. Supported formats are pcm, wav, amr, and m4a (note: m4a is only supported in the 'Speed Version').
    • DEV_PID: The model ID.
      • Use 1537 for Mandarin (Input Method model).
      • Use 1737 for English.

    Example: Testing a 16k AMR file

    FILE="16k-23850.amr"
    FORMAT="amr"
    DEV_PID="1537"
  5. Use a Custom Trained Model (Self-Training Platform)

    master

    When using a model from the self-training platform, you must provide both a DEV_PID (typically 8001) and a LM_ID (Language Model ID) provided by the platform. Uncomment the relevant configuration block in AsrMain.java to include the lm_id in the request URL.

    private int LM_ID;
    
    {
        DEV_PID = 8001;
        LM_ID = 1234;
    }
    
    // The URL construction will use the LM_ID
    String url2 = URL + "?cuid=" + ConnUtil.urlEncode(CUID) + "&dev_pid=" + DEV_PID + "&lm_id=" + LM_ID + "&token=" + token;
  6. Test the REST API ASR via Python script

    master

    This project provides Python scripts (asr_json.py or asr_raw.py) to test the Automatic Speech Recognition (ASR) REST API. It supports Python 2.7 and Python 3.7+.

    To perform recognition, you must provide your application credentials (API_KEY and SECRET_KEY) obtained from the web console. Results are typically output to the console or saved to result.txt (recommended for Windows users to avoid encoding issues).

    python asr_json.py
  7. Set up Postman for ASR testing

    master

    To test the ASR (Automatic Speech Recognition) REST API using Postman, follow these steps:

    1. Import the Collection: Open Postman, click Import, select Choose Files, and select the postman_collection.json file located in the same directory as this guide.
    2. Authenticate:
      • Locate your App Key (client_id) and App Secret (client_secret) from the Baidu Speech Application Management console.
      • In Postman, select the Token icon and the first request: POST token.
      • Enter your client_id and client_secret into the corresponding fields.
      • Click SEND to obtain a new token.
    3. Use the Token: Use the returned token in subsequent requests (e.g., POST asr_raw).
    # Example Token Request Setup
    # client_id: YOUR_APP_KEY
    # client_secret: YOUR_APP_SECRET
  8. Get Access Token

    master

    Before calling the ASR API, you must obtain an authentication token.

    1. In the imported collection, select the request named POST token.
    2. Enter your credentials in the request parameters:
      • client_id: Your App KEY from the official console.
      • client_secret: Your App Secret from the official console.
    3. Click Send.

    Response Format: An access token string will be returned, for example: 24.e12f4404d743f08214074a7c0cf36cf4.2592000.1563701134.282335-15803531

    Important Note: The Access Token is valid for 2592000 seconds. Ensure your application periodically requests a new token to avoid expiration.

  9. Run the ASR recognition test with asr.sh

    master

    Execute the asr.sh script to perform speech recognition.

    To debug the script execution and see step-by-step command processing, use the -x flag.

    Expected Token Response: When the script fetches a token, ensure the scope field contains audio_voice_assistant_get. If it does not, you must activate this capability in the web console.

    Expected ASR Result Format: Successful recognition returns a JSON object containing the transcribed text in the result array.

    # Standard execution
    sh asr.sh
    
    # Debug mode
    sh -x asr.sh
  10. Test different audio files and formats

    master

    To test different audio files, modify the $AUDIO_FILE and $FORMAT variables in the script. Supported formats include pcm, wav, amr, and m4a.

    Example: Testing a specific AMR file

    # The path to the file to be recognized
    $AUDIO_FILE = "./16k-23850.amr";
    # The file extension/format
    $FORMAT = "amr";

    Example: Testing English language To switch the recognition language to English, modify the dev_pid:

    $dev_pid = 1737;
    $AUDIO_FILE = "./16k-23850.amr";
    $FORMAT = "amr";
    $dev_pid = 1737;