Unity 工具 之 Azure 微軟SSML語音合成TTS流式獲取音頻數據的簡單整理

Unity 工具 之 Azure 微軟SSML語音合成TTS流式獲取音頻數據的簡單整理

目錄

Unity 工具 之 Azure 微軟SSML語音合成TTS流式獲取音頻數據的簡單整理

一、簡單介紹

二、實現原理

三、實現步驟

四、關鍵代碼


一、簡單介紹

Unity 工具類,自己整理的一些游戲開發可能用到的模塊,單獨獨立使用,方便游戲開發。

本節介紹,這里在使用微軟的Azure 進行語音合成的兩個方法的做簡單整理,這里簡單說明,如果你有更好的方法,歡迎留言交流。

語音合成標記語言 (SSML) 是一種基于 XML 的標記語言,可用于微調文本轉語音輸出屬性,例如音調、發音、語速、音量等。 與純文本輸入相比,你擁有更大的控制權和靈活性。

可以使用 SSML 來執行以下操作:

  • 定義輸入文本結構,用于確定文本轉語音輸出的結構、內容和其他特征。 例如,可以使用 SSML 來定義段落、句子、中斷/暫停或靜音。 可以使用事件標記(例如書簽或視素)來包裝文本,這些標記可以稍后由應用程序處理。
  • 選擇語音、語言、名稱、樣式和角色。 可以在單個 SSML 文檔中使用多個語音。 調整重音、語速、音調和音量。 還可以使用 SSML 插入預先錄制的音頻,例如音效或音符。
  • 控制輸出音頻的發音。 例如,可以將 SSML 與音素和自定義詞典配合使用來改進發音。 還可以使用 SSML 定義單詞或數學表達式的具體發音。
下面是 SSML 文檔的基本結構和語法的子集:
?
<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="string"><mstts:backgroundaudio src="string" volume="string" fadein="string" fadeout="string"/><voice name="string" effect="string"><audio src="string"></audio><bookmark mark="string"/><break strength="string" time="string" /><emphasis level="value"></emphasis><lang xml:lang="string"></lang><lexicon uri="string"/><math xmlns="http://www.w3.org/1998/Math/MathML"></math><mstts:audioduration value="string"/><mstts:express-as style="string" styledegree="value" role="string"></mstts:express-as><mstts:silence type="string" value="string"/><mstts:viseme type="string"/><p></p><phoneme alphabet="string" ph="string"></phoneme><prosody pitch="value" contour="value" range="value" rate="value" volume="value"></prosody><s></s><say-as interpret-as="string" format="string" detail="string"></say-as><sub alias="string"></sub></voice>
</speak>

?SSML 語音和聲音
語音合成標記語言 (SSML) 的語音和聲音 - 語音服務 - Azure AI services | Microsoft Learn

官網注冊:

面向學生的 Azure - 免費帳戶額度 | Microsoft Azure

官網技術文檔網址:

技術文檔 | Microsoft Learn

官網的TTS:

文本轉語音快速入門 - 語音服務 - Azure Cognitive Services | Microsoft Learn

Azure Unity SDK? 包官網:

安裝語音 SDK - Azure Cognitive Services | Microsoft Learn

SDK具體鏈接:

https://aka.ms/csspeech/unitypackage
?

二、實現原理

1、官網申請得到語音合成對應的 SPEECH_KEY 和 SPEECH_REGION

2、然后對應設置 語言 和需要的聲音 配置

3、使用 SSML 帶有流式獲取得到音頻數據,在聲源中播放或者保存即可,樣例如下

public static async Task SynthesizeAudioAsync()
{var speechConfig = SpeechConfig.FromSubscription("YourSpeechKey", "YourSpeechRegion");using var speechSynthesizer = new SpeechSynthesizer(speechConfig, null);var ssml = File.ReadAllText("./ssml.xml");var result = await speechSynthesizer.SpeakSsmlAsync(ssml);using var stream = AudioDataStream.FromResult(result);await stream.SaveToWaveFileAsync("path/to/write/file.wav");
}

三、實現步驟

基礎的環境搭建參照:Unity 工具 之 Azure 微軟語音合成普通方式和流式獲取音頻數據的簡單整理_unity 語音合成

1、腳本實現,掛載對應腳本到場景中

2、運行場景,會使用 SSML方式合成TTS,并播放

?

四、關鍵代碼

1、AzureTTSDataWithSSMLHandler

using Microsoft.CognitiveServices.Speech;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using UnityEngine;/// <summary>
/// 使用 SSML 方式語音合成
/// </summary>
public class AzureTTSDataWithSSMLHandler
{/// <summary>/// Azure TTS 合成 必要數據/// </summary>private const string SPEECH_KEY = "YOUR_SPEECH_KEY";private const string SPEECH_REGION = "YOUR_SPEECH_REGION";private const string SPEECH_RECOGNITION_LANGUAGE = "zh-CN";private string SPEECH_VOICE_NAME = "zh-CN-XiaoxiaoNeural";/// <summary>/// 創建 TTS 中的參數/// </summary>private CancellationTokenSource m_CancellationTokenSource;private AudioDataStream m_AudioDataStream;private Connection m_Connection;private SpeechConfig m_Config;private SpeechSynthesizer m_Synthesizer;/// <summary>/// 音頻獲取事件/// </summary>private Action<AudioDataStream> m_AudioStream;/// <summary>/// 開始播放TTS事件/// </summary>private Action m_StartTTSPlayAction;/// <summary>/// 停止播放TTS事件/// </summary>private Action m_StartTTSStopAction;/// <summary>/// 初始化/// </summary>public void Initialized(){m_Config = SpeechConfig.FromSubscription(SPEECH_KEY, SPEECH_REGION);m_Synthesizer = new SpeechSynthesizer(m_Config, null);m_Connection = Connection.FromSpeechSynthesizer(m_Synthesizer);m_Connection.Open(true);}/// <summary>/// 開始進行語音合成/// </summary>/// <param name="msg">合成的內容</param>/// <param name="stream">獲取到的音頻流數據</param>/// <param name="style"></param>public async void Start(string msg, Action<AudioDataStream> stream, string style = "chat"){this.m_AudioStream = stream;await SynthesizeAudioAsync(CreateSSML(msg, SPEECH_RECOGNITION_LANGUAGE, SPEECH_VOICE_NAME, style));}/// <summary>/// 停止語音合成/// </summary>public void Stop(){m_StartTTSStopAction?.Invoke();if (m_AudioDataStream != null){m_AudioDataStream.Dispose();m_AudioDataStream = null;}if (m_CancellationTokenSource != null){m_CancellationTokenSource.Cancel();}if (m_Synthesizer != null){m_Synthesizer.Dispose();m_Synthesizer = null;}if (m_Connection != null){m_Connection.Dispose();m_Connection = null;}}/// <summary>/// 設置語音合成開始播放事件/// </summary>/// <param name="onStartAction"></param>public void SetStartTTSPlayAction(Action onStartAction){if (onStartAction != null){m_StartTTSPlayAction = onStartAction;}}/// <summary>/// 設置停止語音合成事件/// </summary>/// <param name="onAudioStopAction"></param>public void SetStartTTSStopAction(Action onAudioStopAction){if (onAudioStopAction != null){m_StartTTSStopAction = onAudioStopAction;}}/// <summary>/// 開始異步請求合成 TTS 數據/// </summary>/// <param name="speakMsg"></param>/// <returns></returns>private async Task SynthesizeAudioAsync(string speakMsg){Cancel();m_CancellationTokenSource = new CancellationTokenSource();var result = m_Synthesizer.StartSpeakingSsmlAsync(speakMsg);await result;m_StartTTSPlayAction?.Invoke();m_AudioDataStream = AudioDataStream.FromResult(result.Result);m_AudioStream?.Invoke(m_AudioDataStream);}private void Cancel(){if (m_AudioDataStream != null){m_AudioDataStream.Dispose();m_AudioDataStream = null;}if (m_CancellationTokenSource != null){m_CancellationTokenSource.Cancel();}}/// <summary>/// 生成 需要的 SSML XML 數據/// (格式不唯一,可以根據需要自行在增加刪減)/// </summary>/// <param name="msg">合成的音頻內容</param>/// <param name="language">合成語音</param>/// <param name="voiceName">采用誰的聲音合成音頻</param>/// <param name="style">合成時的語氣類型</param>/// <returns>ssml XML</returns>private string CreateSSML(string msg, string language, string voiceName, string style = "chat"){// XmlDocumentXmlDocument xmlDoc = new XmlDocument();// 設置 speak 基礎元素XmlElement speakElem = xmlDoc.CreateElement("speak");speakElem.SetAttribute("version", "1.0");speakElem.SetAttribute("xmlns", "http://www.w3.org/2001/10/synthesis");speakElem.SetAttribute("xmlns:mstts", "http://www.w3.org/2001/mstts");speakElem.SetAttribute("xml:lang", language);// 設置 voice 元素XmlElement voiceElem = xmlDoc.CreateElement("voice");voiceElem.SetAttribute("name", voiceName);// 設置 mstts:viseme 元素XmlElement visemeElem = xmlDoc.CreateElement("mstts", "viseme", "http://www.w3.org/2001/mstts");visemeElem.SetAttribute("type", "FacialExpression");// 設置 語氣 元素XmlElement styleElem = xmlDoc.CreateElement("mstts", "express-as", "http://www.w3.org/2001/mstts");styleElem.SetAttribute("style", style.ToString().Replace("_", "-"));// 創建文本節點,包含文本信息XmlNode textNode = xmlDoc.CreateTextNode(msg);// 設置好的元素添加到 xml 中voiceElem.AppendChild(visemeElem);styleElem.AppendChild(textNode);voiceElem.AppendChild(styleElem);speakElem.AppendChild(voiceElem);xmlDoc.AppendChild(speakElem);Debug.Log("[SSML  XML] Result : " + xmlDoc.OuterXml);return xmlDoc.OuterXml;}}

2、AzureTTSMono

using Microsoft.CognitiveServices.Speech;
using System;
using System.Collections.Concurrent;
using System.IO;
using UnityEngine;[RequireComponent(typeof(AudioSource))]
public class AzureTTSMono : MonoBehaviour
{private AzureTTSDataWithSSMLHandler m_AzureTTSDataWithSSMLHandler;/// <summary>/// 音源和音頻參數/// </summary>private AudioSource m_AudioSource;private AudioClip m_AudioClip;/// <summary>/// 音頻流數據/// </summary>private ConcurrentQueue<float[]> m_AudioDataQueue = new ConcurrentQueue<float[]>();private AudioDataStream m_AudioDataStream;/// <summary>/// 音頻播放完的事件/// </summary>private Action m_AudioEndAction;/// <summary>/// 音頻播放結束的布爾變量/// </summary>private bool m_NeedPlay = false;private bool m_StreamReadEnd = false;private const int m_SampleRate = 16000;//最大支持60s音頻 private const int m_BufferSize = m_SampleRate * 60;//采樣容量private const int m_UpdateSize = m_SampleRate;//audioclip 設置過的數據個數private int m_TotalCount = 0;private int m_DataIndex = 0;#region Lifecycle functionprivate void Awake(){m_AudioSource = GetComponent<AudioSource>();m_AzureTTSDataWithSSMLHandler = new AzureTTSDataWithSSMLHandler();m_AzureTTSDataWithSSMLHandler.SetStartTTSPlayAction(() => { Debug.Log(" Play TTS "); });m_AzureTTSDataWithSSMLHandler.SetStartTTSStopAction(() => { Debug.Log(" Stop TTS "); AudioPlayEndEvent(); });m_AudioEndAction = () => { Debug.Log(" End TTS "); };m_AzureTTSDataWithSSMLHandler.Initialized();}// Start is called before the first frame updatevoid Start(){m_AzureTTSDataWithSSMLHandler.Start("今朝有酒,今朝醉,人生幾年百花春", OnGetAudioStream);}// Update is called once per frameprivate void Update(){UpdateAudio();}#endregion#region Audio handler/// <summary>/// 設置播放TTS的結束的結束事件/// </summary>/// <param name="act"></param>public void SetAudioEndAction(Action act){this.m_AudioEndAction = act;}/// <summary>/// 處理獲取到的TTS流式數據/// </summary>/// <param name="stream">流數據</param>public async void OnGetAudioStream(AudioDataStream stream){m_StreamReadEnd = false;m_NeedPlay = true;m_AudioDataStream = stream;Debug.Log("[AzureTTSMono] OnGetAudioStream");MemoryStream memStream = new MemoryStream();byte[] buffer = new byte[m_UpdateSize * 2];uint bytesRead;m_DataIndex = 0;m_TotalCount = 0;m_AudioDataQueue.Clear();// 回到主線程進行數據處理Loom.QueueOnMainThread(() =>{m_AudioSource.Stop();m_AudioSource.clip = null;m_AudioClip = AudioClip.Create("SynthesizedAudio", m_BufferSize, 1, m_SampleRate, false);m_AudioSource.clip = m_AudioClip;});do{bytesRead = await System.Threading.Tasks.Task.Run(() => m_AudioDataStream.ReadData(buffer));if (bytesRead <= 0){break;}// 讀取寫入數據memStream.Write(buffer, 0, (int)bytesRead);{var tempData = memStream.ToArray();var audioData = new float[memStream.Length / 2];for (int i = 0; i < audioData.Length; ++i){audioData[i] = (short)(tempData[i * 2 + 1] << 8 | tempData[i * 2]) / 32768.0F;}try{m_TotalCount += audioData.Length;// 把數據添加到隊列中m_AudioDataQueue.Enqueue(audioData);// new 獲取新的地址,為后面寫入數據memStream = new MemoryStream();}catch (Exception e){Debug.LogError(e.ToString());}}} while (bytesRead > 0);m_StreamReadEnd = true;}/// <summary>/// Update 播放音頻/// </summary>private void UpdateAudio() {if (!m_NeedPlay) return;//數據操作if (m_AudioDataQueue.TryDequeue(out float[] audioData)){m_AudioClip.SetData(audioData, m_DataIndex);m_DataIndex = (m_DataIndex + audioData.Length) % m_BufferSize;}//檢測是否停止if (m_StreamReadEnd && m_AudioSource.timeSamples >= m_TotalCount){AudioPlayEndEvent();}if (!m_NeedPlay) return;//由于網絡,可能額有些數據還沒有過來,所以根據需要判斷是否暫停播放if (m_AudioSource.timeSamples >= m_DataIndex && m_AudioSource.isPlaying){m_AudioSource.timeSamples = m_DataIndex;//暫停Debug.Log("[AzureTTSMono] Pause");m_AudioSource.Pause();}//由于網絡,可能有些數據過來比較晚,所以這里根據需要判斷是否繼續播放if (m_AudioSource.timeSamples < m_DataIndex && !m_AudioSource.isPlaying){//播放Debug.Log("[AzureTTSMono] Play");m_AudioSource.Play();}}/// <summary>/// TTS 播放結束的事件/// </summary>private void AudioPlayEndEvent(){Debug.Log("[AzureTTSMono] End");m_NeedPlay = false;m_AudioSource.timeSamples = 0;m_AudioSource.Stop();m_AudioEndAction?.Invoke();}#endregion
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/43634.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/43634.shtml
英文地址,請注明出處:http://en.pswp.cn/news/43634.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Qt creator之對齊參考線——新增可視化縮進功能

Qt creator隨著官方越來越重視&#xff0c;更新頻率也在不斷加快&#xff0c;今天無意中發現qt creator新版有了對齊參考線&#xff0c;也稱可視化縮進Visualize Indent&#xff0c;默認為啟用狀態。 下圖為舊版Qt Creator顯示設置欄&#xff1a; 下圖為新版本Qt Creator顯示設…

Day14 01-Shell腳本編程詳解

文章目錄 第一章 Shell編程【重點】1.1. Shell的概念介紹1.1.1. 命令解釋器4.1.1.2. Shell腳本 1.2. Shell編程規范1.2.1. 腳本文件的結構1.2.2. 腳本文件的執行 1.3. Shell的變量1.3.1. 變量的用法1.3.2. 變量的分類1.3.3. 局部變量1.3.4. 環境變量1.3.5. 位置參數變量1.3.6. …

Python入門【內存管理機制、Python緩存機制、垃圾回收機制、分代回收機制】(三十二)

&#x1f44f;作者簡介&#xff1a;大家好&#xff0c;我是愛敲代碼的小王&#xff0c;CSDN博客博主,Python小白 &#x1f4d5;系列專欄&#xff1a;python入門到實戰、Python爬蟲開發、Python辦公自動化、Python數據分析、Python前后端開發 &#x1f4e7;如果文章知識點有錯誤…

LeetCode150道面試經典題-- 存在重復元素 II(簡單)

1.題目 給你一個整數數組 nums 和一個整數 k &#xff0c;判斷數組中是否存在兩個 不同的索引 i 和 j &#xff0c;滿足 nums[i] nums[j] 且 abs(i - j) < k 。如果存在&#xff0c;返回 true &#xff1b;否則&#xff0c;返回 false 。 2.示例 示例 1&#xff1a; 輸…

CSS中的字體屬性有哪些值,并分別描述它們的作用。

聚沙成塔每天進步一點點 ? 專欄簡介? font-style? font-weight? font-size? font-family? font-variant? line-height? letter-spacing? word-spacing? font? 寫在最后 ? 專欄簡介 前端入門之旅&#xff1a;探索Web開發的奇妙世界 記得點擊上方或者右側鏈接訂閱本專…

JS中對象數組深拷貝方法

structuredClone() JavaScript 中提供了一個原生 API 來執行對象的深拷貝&#xff1a;structuredClone。它可以通過結構化克隆算法創建一個給定值的深拷貝&#xff0c;并且還可以傳輸原始值的可轉移對象。 當對象中存在循環引用時&#xff0c;仍然可以通過 structuredClone()…

過濾字符,繞過

構造不包含字母和數字的webshell <?phpecho "A"^""; ?>運行結果為! 代碼中對字符"A"和字符”"進行了異或操作。在PHP中&#xff0c;兩個變量進行異或時&#xff0c;先會將字符串轉換成ASCII值&#xff0c;再將ASCII值轉換成二進制…

容器docker安裝及應用

目錄 二進制安裝docker應用啟動docker拉取鏡像查看當前主機鏡像查看鏡像詳細信息運行容器 二進制安裝docker 環境 centos 7 [rootlocalhost ~]# mkdir /data [rootlocalhost ~]# wget -P /data/ https://download.docker.com/linux/static/stable/x86_64/docker-18.03.1-ce.t…

【聲波】聲波在硼酸、硫酸鎂 (MgSO4) 和純水中的吸收研究(Matlab代碼實現)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;歡迎來到本博客????&#x1f4a5;&#x1f4a5; &#x1f3c6;博主優勢&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客內容盡量做到思維縝密&#xff0c;邏輯清晰&#xff0c;為了方便讀者。 ??座右銘&a…

MAC 命令行啟動tomcat的詳細介紹

MAC 命令行啟動tomcat MAC 命令行啟動tomcat的詳細介紹 一、修改授權 進入tomcat的bin目錄,修改授權 1 2 3 ? bin pwd /Users/yp/Documents/workspace/apache-tomcat-7.0.68/bin ? bin sudo chmod 755 *.sh sudo為系統超級管理員權限.chmod 改變一個或多個文件的存取模…

2.js中attr()用來修改或者添加屬性或者屬性值

attr()可以用來修改或者添加屬性或者屬性值 例&#xff1a;<input type"button" class"btn btn-info" id"subbtn" style"font-size:12px" value"我也說一句"/>1.如果想獲取input中value的值 $(#subbtn).attr(value);…

ASP.NET Core中路由規則匹配

RESTful約束&#xff0c;如果在一個控制器里面有多個Get、Post...的操作 1、在一個控制器里面可以定義多個API方法 2、通過路由規則來區分 /// <summary> /// 獲取用戶信息 /// </summary> /// <param name"user"></param> /// <returns…

c++ | 字節轉換 | 字長 | 機器位數

為什么有的時候腦子轉不過來&#xff1f;&#xff1f; 為什么要對字節、機器長啊、位啊都要門清 位數 一般的就是指計算機的位數&#xff0c;比如64位/32位&#xff0c;更簡單的理解&#xff0c;計算機就是在不停的做二進制的計算&#xff0c;比如32位計算機&#xff0c;在長…

[保研/考研機試] KY26 10進制 VS 2進制 清華大學復試上機題 C++實現

題目鏈接&#xff1a; 10進制 VS 2進制http://www.nowcoder.com/share/jump/437195121691738172415 描述 對于一個十進制數A&#xff0c;將A轉換為二進制數&#xff0c;然后按位逆序排列&#xff0c;再轉換為十進制數B&#xff0c;我們稱B為A的二進制逆序數。 例如對于十進制…

算法基礎課——基礎算法(模板整理)

快速排序 快速排序 #include <iostream> #include <algorithm> using namespace std; int n; int s[100000]; int main() {cin>>n;for(int i0;i<n;i){cin>>s[i];}sort(s,sn);for(int i0;i<n;i){cout<<s[i]<<" ";}cout<…

4.物聯網LWIP之C/S編程

LWIP配置 服務器端實現 客戶端實現 錯誤分析 一。LWIP配置&#xff08;FREERTOS配置&#xff0c;ETH配置&#xff0c;LWIP配置&#xff09; 1.FREERTOS配置 為什么要修改定時源為Tim1&#xff1f;不用systick&#xff1f; 原因&#xff1a;HAL庫與FREERTOS都需要使用systi…

leetcode做題筆記89. 格雷編碼

n 位格雷碼序列 是一個由 2n 個整數組成的序列&#xff0c;其中&#xff1a; 每個整數都在范圍 [0, 2n - 1] 內&#xff08;含 0 和 2n - 1&#xff09;第一個整數是 0一個整數在序列中出現 不超過一次每對 相鄰 整數的二進制表示 恰好一位不同 &#xff0c;且第一個 和 最后一…

C語言好題解析(三)

目錄 選擇題一選擇題二選擇題三選擇題四編程題一編程題二 選擇題一 以下程序段的輸出結果是&#xff08;&#xff09;#include<stdio.h> int main() { char s[] "\\123456\123456\t"; printf("%d\n", strlen(s)); return 0; }A: 12 B: 13 …

Lnton羚通關于【PyTorch】教程:torchvision 目標檢測微調

torchvision 目標檢測微調 本教程將使用Penn-Fudan Database for Pedestrian Detection and Segmentation 微調 預訓練的Mask R-CNN 模型。 它包含 170 張圖片&#xff0c;345 個行人實例。 定義數據集 用于訓練目標檢測、實例分割和人物關鍵點檢測的參考腳本允許輕松支持添加…

前端-輪詢

一、輪詢定義 輪詢是指在一定的時間間隔內&#xff0c;定時向服務器發送請求&#xff0c;獲取最新數據的過程。輪詢通常用于從服務器獲取實時更新的數據。 二、輪詢和長輪詢區別 輪詢是在固定的時間間隔內向服務器發送請求&#xff0c;即使服務器沒有數據更新也會繼續發送請求…