Unity Sherpa-onnx 笔记
概要:这篇主要记录自己尝试使用Sherpa-onnx在Unity中实现语音合成过程中遇到的一些问题。
一、 开发环境与测试平台
1. 开发环境
unity 版本:2021.3.23f1
2. 测试平台
window平台:window10
android平板:荣耀平板x8pro、Android13、6GB+5GB、128GB、X86架构。
android手机:荣耀畅玩20、KOZ-AL00,android10、6GB、128GB
二、官方文档
1. sherpa-onnx官网(https://k2-fsa.github.io/sherpa/onnx/index.html)
文本转语音模型列表:
文本转语音模型下载:
点击上图表格中的模型定位到模型详细页面,前面的wget、tar、rm是linux命令,直接复制后面的链接下载解压模型包即可。
文本转语音模型预览
往下拉一点都会有此模型包的音色预览。
3. github仓库(https://github.com/k2-fsa/sherpa-onnx)
这个仓库不是Unity项目,都有些什么以后在研究
4. github仓库-unity 项目(https://github.com/xue-fei/sherpa-onnx-unity)
往下拉,在README中找到Unity案例的链接
下载项目、解压、unity hub打开、切换版本(提示版本不一致继续就行)、这里都跳过了。
三、运行项目
下面是在Unity中打开的项目
其它就不多说了,只说影响运行的几个细节:
1. 刚刚下载的模型必须要放在StreamingAssets/models下,否则在Unity2021版本中即使放了模型文件,配置也正确,运行后也会闪退。
2. 修改SpeechSynthesis.cs脚本,根据下载的模型修改Start方法中的根目录和Init方法中参数配置
3. 案例中没有很好的对模型文件路径配置进行检查,导致这点小问题都要闪退的,很烦,所以我参考了其它文章修改了下
using AOT;
using SherpaOnnx;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;[RequireComponent(typeof(AudioSource))]
public class SpeechSynthesis : MonoBehaviour
{[SerializeField]private float lengthScale = 1;OfflineTts ot;OfflineTtsGeneratedAudio otga;OfflineTtsConfig config;OfflineTtsCallback otc;static SpeechSynthesis Instance;AudioSource audioSource;int SampleRate = 22050;AudioClip audioClip = null;List<float> audioData = new List<float>();/// <summary>/// 当前要读取的索引位置/// </summary>int curAudioClipPos = 0;public bool initDone = false;public float audioLength = 0f;public Action OnAudioEnd;string pathRoot;// Start is called before the first frame updatevoid Start(){pathRoot = Util.GetPath() + "/models/sherpa-onnx-vits-zh-ll/";audioSource = GetComponent<AudioSource>();Loom.RunAsync(() =>{Init();});}private void Update(){if (audioLength > 0){audioLength -= Time.deltaTime;if (audioLength < 0){audioLength = 0;Debug.Log("音频播放完毕");if (OnAudioEnd != null){OnAudioEnd();}}}}void Init(){initDone = false;try {Debug.Log("准备初始化文本转语音\n根目录: " + pathRoot);Instance = this;config = new OfflineTtsConfig();config.Model.Vits.Model = Path.Combine(pathRoot, "model.onnx");config.Model.Vits.Lexicon = Path.Combine(pathRoot, "lexicon.txt");config.Model.Vits.Tokens = Path.Combine(pathRoot, "tokens.txt");config.Model.Vits.DictDir = Path.Combine(pathRoot, "dict");string[] ruleFsts = { "phone.fst", "date.fst", "number.fst" };StringBuilder sb = new StringBuilder();for (int i = 0; i < ruleFsts.Length; i++){sb.Append(pathRoot).Append(ruleFsts[i]);if (i != ruleFsts.Length - 1)sb.Append(',');}config.RuleFsts = sb.ToString();config.Model.Vits.LengthScale = lengthScale;config.Model.NumThreads = 4;config.Model.Debug = 1;config.Model.Provider = "cpu";if (ValidateConfiguration()){ot = new OfflineTts(config);SampleRate = ot.SampleRate;otc = new OfflineTtsCallback(OnStaticAudioData);initDone = true;Loom.QueueOnMainThread(() =>{Debug.Log("文字转语音初始化完成");Generate("文字转语音初始化完成", 1, 1);});}else{Debug.LogError("配置验证不通过!");}}catch (Exception e){Loom.QueueOnMainThread(() =>{Debug.LogError("初始化文字转语音失败!\n" + e.Message);});}}/// <summary>/// 验证配置/// </summary>private bool ValidateConfiguration(){bool pass = true;if (!File.Exists(config.Model.Vits.Model)){Debug.LogError("模型文件不存在: " + config.Model.Kokoro.Model);pass = false;}if (!File.Exists(config.Model.Vits.Lexicon)){Debug.LogError("词典文件不存在: " + config.Model.Kokoro.Lexicon);pass = false;}if (!File.Exists(config.Model.Vits.Tokens)){Debug.LogError("tokens文件不存在: " + config.Model.Vits.Tokens);pass = false;}if (!Directory.Exists(config.Model.Vits.DictDir)){Debug.LogError("字典目录不存在: " + config.Model.Vits.DictDir);pass = false;}string[] ruleFsts = config.RuleFsts.Split(",");for (int i = 0; i < ruleFsts.Length; i++){if (!File.Exists(ruleFsts[i])){Debug.LogError("ruleFsts文件不存在: " + ruleFsts[i]);pass = false;}}return pass;}public void Generate(string text, float speed, int speakerId){if (!initDone){Debug.LogWarning("文字转语音未完成初始化");return;}Loom.RunAsync(() =>{otga = ot.GenerateWithCallback(text, speed, speakerId, otc);});}[MonoPInvokeCallback(typeof(OfflineTtsCallback))]static int OnStaticAudioData(IntPtr samples, int n){return Instance.OnAudioData(samples, n);}private int OnAudioData(IntPtr samples, int n){float[] tempData = new float[n];Marshal.Copy(samples, tempData, 0, n);audioData.AddRange(tempData);Loom.QueueOnMainThread(() =>{audioLength += (float)n / (float)SampleRate;if (!audioSource.isPlaying && audioData.Count > SampleRate * 2){audioClip = AudioClip.Create("SynthesizedAudio", SampleRate * 2, 1,SampleRate, true, (float[] data) =>{ExtractAudioData(data);});audioSource.clip = audioClip;audioSource.loop = true;audioSource.Play();}});return n;}bool ExtractAudioData(float[] data){if (data == null || data.Length == 0){return false;}bool hasData = false;//是否真的读取到数据int dataIndex = 0;//当前要写入的索引位置if (audioData != null && audioData.Count > 0){while (curAudioClipPos < audioData.Count && dataIndex < data.Length){data[dataIndex] = audioData[curAudioClipPos];curAudioClipPos++;dataIndex++;hasData = true;}}//剩余部分填0while (dataIndex < data.Length){data[dataIndex] = 0;dataIndex++;}return hasData;}private void OnDestroy(){if (audioSource != null && audioSource.isPlaying){audioSource.Stop();}if (ot != null){ot.Dispose();}if (otc != null){otc = null;}if (otga != null){otga.Dispose();}}
}
4. 打包安卓需要把模型文件复制到设备中,StreamingAssets是不会被打包进去的,而且安卓中也无法读取,参考哔哩哔哩13:00的视频:
四、问题
开始我下的是哔哔哩up主的项目,打包到安卓后会一直提示初始化失败: sherpa-onnx-c-api assembly: type: member:(null)
各种方法都试了不行,重新下载动态库,根据设备的架构选择动态库什么的没用,修改了gradleTemplate、和mainTemplate也没用,甚至开始的时候安卓打包也出错了:What went wrong: A problem occurred evaluating project ‘:unityLibrary’. > Could not find method namespace() for arguments [com.unity3d.player] on extension ‘android’ of type com.android.build.gradle.LibraryExtension.