TTS Text-to-speech(文字转语音)服务

红目香薰
大数据领域优质创作者
博客专家认证
2021-11-18 23:51:46

目录

 中文帮助文档:

创建语音资源:

 填写注册信息:

转到资源服务

 编写测试代码(C#):

C#需要的包【NuGet搜索:CognitiveServices】

 视频连接:


官网链接:Speech Studio - Microsoft Azure (https://speech.azure.cn/audiocontentcreation)

 中文帮助文档:

https://docs.microsoft.com/zh-cn/azure/cognitive-services/speech-service/get-started-text-to-speech?tabs=script%2Cwindowsinstall&pivots=programming-language-csharp

创建语音资源:

 填写注册信息:

转到资源服务

 编写测试代码(C#):

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;

namespace test1118
{
    public class Program
    {
        static async Task Main()
        {
            await SynthesizeAudioAsync();
        }
        static async Task SynthesizeAudioAsync()
        {
            //秘钥换成自己的
            var config = SpeechConfig.FromSubscription(
                "b88f6907c8f64075a6169dc4d7dff65a",
                "chinanorth2"
                );
            using var audioConfig = AudioConfig.FromWavFileOutput("file1.wav");
            using var synthesizer = new SpeechSynthesizer(config, audioConfig);
            await synthesizer.SpeakTextAsync(" I HAVE A DREAM.");
        }
    }
}

C#需要的包【NuGet搜索:CognitiveServices】

 

 执行效果:


用JavaScript也很方便。 但是需要PHP的环境

【index.html】代码

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Microsoft Cognitive Services Speech SDK JavaScript Quickstart</title>
  <meta charset="utf-8" />
  <style>
    body {
      font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, 'Roboto', 'Helvetica Neue', sans-serif;
      font-size: 14px;
    }

    table, th, td {
      border: 1px solid #f1f1f1;
      border-collapse: collapse;
    }

    th, td {
      padding: 10px;
    }

    .mode {
      font-size: 18px;
    }

    input:not(disabled) {
      font-weight: bold;
      color: black;
    }

    button {
      padding: 4px 8px;
      background: #0078d4;
      color: #ffffff;
    }

    button:disabled {
      padding: 4px 8px;
      background: #ccc;
      color: #666;
    }

    input[type=radio] {
      position: relative;
      z-index: 1;
    }

    input[type=radio] + label {
      padding: 8px 4px 8px 30px;
      margin-left: -30px;
    }

    input[type=radio]:checked + label {
      background: #0078d4;
      color: #ffffff;
    }
  </style>
</head>
<body style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:13px;">
  <div id="warning">
    <h1 style="font-weight:500;">Speech Recognition Speech SDK not found (microsoft.cognitiveservices.speech.sdk.bundle.js missing).</h1>
  </div>
  
  <div id="content" style="display:none">
    <table width="100%">
      <tr>
        <td></td>
        <td><h1 style="font-weight:500;">Microsoft Cognitive Services Speech SDK JavaScript Quickstart</h1></td>
      </tr>
      <tr>
        <td align="right"><a href="https://docs.microsoft.com/azure/cognitive-services/speech-service/get-started" target="_blank">Subscription</a>:</td>
        <td><input id="subscriptionKey" type="text" size="40" placeholder="YourSubscriptionKey"></td>
      </tr>
      <tr>
        <td align="right">Region</td>
        <td><input id="serviceRegion" type="text" size="40" placeholder="YourServiceRegion"></td>
      </tr>
      <tr>
        <td align="right" valign="top">Input Text</td>
        <td><textarea id="phraseDiv" style="display: inline-block;width:500px;height:50px"></textarea></td>
      </tr>
      <tr>
        <td></td>
        <td><button id="startSpeakTextAsyncButton">Start Text to Speech</button></td>
      </tr>
      <tr>
        <td align="right" valign="top">Result</td>
        <td><textarea id="resultDiv" style="display: inline-block;width:500px;height:100px"></textarea></td>
      </tr>
    </table>
  </div>

  <!-- Speech SDK reference sdk. -->
  <script src="https://aka.ms/csspeech/jsbrowserpackageraw"></script>

  <!-- Speech SDK USAGE -->
  <script>
    // status fields and start button in UI
    var phraseDiv;
    var resultDiv;
    var startSpeakTextAsyncButton;

    // subscription key and region for speech services.
    var subscriptionKey, serviceRegion;
    var SpeechSDK;
    var synthesizer;

    document.addEventListener("DOMContentLoaded", function () {
      startSpeakTextAsyncButton = document.getElementById("startSpeakTextAsyncButton");
      subscriptionKey = document.getElementById("subscriptionKey");
      serviceRegion = document.getElementById("serviceRegion");
      phraseDiv = document.getElementById("phraseDiv");
      resultDiv = document.getElementById("resultDiv");

      startSpeakTextAsyncButton.addEventListener("click", function () {
        startSpeakTextAsyncButton.disabled = true;
        phraseDiv.innerHTML = "";

        if (subscriptionKey.value === "" || subscriptionKey.value === "subscription") {
          alert("Please enter your Microsoft Cognitive Services Speech subscription key!");
          startSpeakTextAsyncButton.disabled = false;
          return;
        }
        var speechConfig = SpeechSDK.SpeechConfig.fromSubscription(subscriptionKey.value, serviceRegion.value);

        synthesizer = new SpeechSDK.SpeechSynthesizer(speechConfig);

        let inputText = phraseDiv.value;
        synthesizer.speakTextAsync(
          inputText,
          function (result) {
            startSpeakTextAsyncButton.disabled = false;
            if (result.reason === SpeechSDK.ResultReason.SynthesizingAudioCompleted) {
              resultDiv.innerHTML += "synthesis finished for [" + inputText + "].\n";
            } else if (result.reason === SpeechSDK.ResultReason.Canceled) {
              resultDiv.innerHTML += "synthesis failed. Error detail: " + result.errorDetails + "\n";
            }
            window.console.log(result);
            synthesizer.close();
            synthesizer = undefined;
          },
          function (err) {
            startSpeakTextAsyncButton.disabled = false;
            resultDiv.innerHTML += "Error: ";
            resultDiv.innerHTML += err;
            resultDiv.innerHTML += "\n";
            window.console.log(err);

            synthesizer.close();
            synthesizer = undefined;
        });
      });

      if (!!window.SpeechSDK) {
        SpeechSDK = window.SpeechSDK;
        startSpeakTextAsyncButton.disabled = false;

        document.getElementById('content').style.display = 'block';
        document.getElementById('warning').style.display = 'none';

        // in case we have a function for getting an authorization token, call it.
        if (typeof RequestAuthorizationToken === "function") {
            RequestAuthorizationToken();
        }
      }
    });
  
  </script>
</body>
</html>

PHP代码:

<?php
header('Access-Control-Allow-Origin: ' . $_SERVER['SERVER_NAME']);

// Replace with your own subscription key and service region (e.g., "westus").
$subscriptionKey = 'YourSubscriptionKey';
$region = 'YourServiceRegion';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://' . $region . '.api.cognitive.microsoft.com/sts/v1.0/issueToken');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{}');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Ocp-Apim-Subscription-Key: ' . $subscriptionKey)); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
echo curl_exec($ch);
?>

测试:

 视频连接:

https://live.csdn.net/v/180699对应使用视频

...全文
2390 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
红目香薰 2021-11-19
  • 打赏
  • 举报
回复

有不恰当的地方欢迎指出啊。大家一起交流。

286

社区成员

发帖
与我相关
我的任务
社区描述
微软公司官方社区。予力众生,成就不凡!微软致力于用技术改变世界,助力企业实现数字化转型。
社区管理员
  • 微软技术栈
  • CSDN官方博客
  • 坚强打工人
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧