快速入门:使用 Node.js 获取“文本转语音”语音的列表Quickstart: Get the list of text-to-speech voices using Node.js

本快速入门介绍如何使用 Node.js 获取某个区域/终结点的标准语音和神经语音的完整列表。In this quickstart, you'll learn how to get the full list of standard and neural voices for a region/endpoint using Node.js. 列表以 JSON 形式返回,语音可用性因区域而异。The list is returned as JSON, and voice availability varies by region. 有关受支持的区域的列表,请参阅区域For a list of supported regions, see regions.

此快速入门需要包含语音服务资源的 Azure 认知服务帐户This quickstart requires an Azure Cognitive Services account with a Speech service resource. 如果没有帐户,可以使用 1 元人民币的试用订阅获取订阅密钥。If you don't have an account, you can use the 1rmb trial to get a subscription key.

先决条件Prerequisites

本快速入门需要:This quickstart requires:

创建项目并声明需要的依赖项Create a project and require dependencies

在你喜欢使用的 IDE 或编辑器中新建一个 Node.js 项目。Create a new Node.js project using your favorite IDE or editor. 然后,将此代码片段复制到项目的名为 get-voices.js 的文件中。Then copy this code snippet into your project in a file named get-voices.js.

// Requires request and request-promise for HTTP requests
// e.g. npm install request request-promise
const rp = require('request-promise');
// Requires fs to write the list of languages to a file
const fs = require('fs');

备注

如果尚未使用这些模块,则需在运行程序之前安装它们。If you haven't used these modules you'll need to install them before running your program. 若要安装这些包,请运行 npm install request request-promiseTo install these packages, run: npm install request request-promise.

获取访问令牌Get an access token

文本转语音 REST API 需要使用访问令牌进行身份验证。The text-to-speech REST API requires an access token for authentication. 若要获取访问令牌,需要进行交换。To get an access token, an exchange is required. 此函数通过 issueToken 终结点使用语音服务订阅密钥来交换访问令牌。This function exchanges your Speech service subscription key for an access token using the issueToken endpoint.

此示例假定语音服务订阅位于“中国东部 2”区域。This sample assumes that your Speech service subscription is in the China East 2 region. 如果使用其他区域,请更新 uri 的值。If you're using a different region, update the value for uri. 如需完整的列表,请参阅区域For a full list, see Regions.

将以下代码复制到项目中:Copy this code into your project:

// Gets an access token.
function getAccessToken(subscriptionKey) {
    let options = {
        method: 'POST',
        uri: 'https://chinaeast2.api.cognitive.azure.cn/sts/v1.0/issueToken',
        headers: {
            'Ocp-Apim-Subscription-Key': subscriptionKey
        }
    }
    return rp(options);
}

在下一部分中,我们将创建用于获取语音列表的函数,并将 JSON 输出保存到文件。In the next section, we'll create the function to get the list of voices and save the JSON output to file.

发出请求并保存响应Make a request and save the response

此处我们将要生成请求并保存返回的语音列表。Here you're going to build the request and save the list of returned voices. 此示例假设使用“美国西部”终结点。This sample assumes you're using the West US endpoint. 如果已将资源注册到其他区域,请务必更新 uriIf your resource is registered to a different region, make sure you update the uri. 有关详细信息,请参阅语音服务区域For more information, see Speech service regions.

接下来,为请求添加所需的标头。Next, add required headers for the request. 最后,向服务发出请求。Finally, you'll make a request to the service. 如果请求成功,并返回 200 状态代码,则响应将写入文件。If the request is successful, and a 200 status code is returned, the response is written to file.

function textToSpeech(accessToken) {
    let options = {
        method: 'GET',
        baseUrl: 'https://chinaeast2.tts.speech.azure.cn/',
        url: 'cognitiveservices/voices/list',
        headers: {
            'Authorization': 'Bearer ' + accessToken,
            'Content-Type': 'application/json'
        }
    }

    let request = rp(options)
        .on('response', (response) => {
            if (response.statusCode === 200) {
                request.pipe(fs.createWriteStream('voices.json'));
                console.log('\nYour file is ready.\n')
            }
        });
    return request;
}

将其放在一起Put it all together

即将完成。You're almost done. 最后一步是创建异步函数。The last step is to create an asynchronous function. 此函数将从环境变量读取订阅密钥、获取令牌、等待请求完成,然后将 JSON 响应写入到文件。This function will read your subscription key from an environment variable, get a token, wait for the request to complete, then write the JSON response to file.

如果不熟悉环境变量,或者首选在测试时将订阅密钥硬编码为字符串,请将 process.env.SPEECH_SERVICE_KEY 替换为字符串形式的订阅密钥。If you're unfamiliar with environment variables or prefer to test with your subscription key hardcoded as a string, replace process.env.SPEECH_SERVICE_KEY with your subscription key as a string.

// Use async and await to get the token before attempting
// to convert text to speech.
async function main() {
    // Reads subscription key from env variable.
    // You can replace this with a string containing your subscription key. If
    // you prefer not to read from an env variable.
    // e.g. const subscriptionKey = "your_key_here";
    const subscriptionKey = process.env.SPEECH_SERVICE_KEY;
    if (!subscriptionKey) {
        throw new Error('Environment variable for your subscription key is not set.')
    };
    try {
        const accessToken = await getAccessToken(subscriptionKey);
        await textToSpeech(accessToken);
    } catch (err) {
        console.log(`Something went wrong: ${err}`);
    }
}

main()

运行示例应用Run the sample app

上述操作完成后,就可以运行示例应用了。That's it, you're ready to run your sample app. 从命令行(或终端会话)导航到项目目录,然后运行以下命令:From the command line (or terminal session), navigate to your project directory and run:

node get-voices.js

清理资源Clean up resources

请务必删除示例应用的源代码中的机密信息,例如订阅密钥。Make sure to remove any confidential information from your sample app's source code, like subscription keys.

后续步骤Next steps

另请参阅See also