AiSound 语音引擎

C# 零基础调用教程 | 单文件实现语音合成

重要:本项目为 32 位程序,编译和运行都需要使用 32 位环境。

一、项目文件

C#调用例子aisound.cs 主代码文件,单文件包含所有功能(DLL调用 + WinForm界面)
build.bat 编译脚本,双击一键生成 exe,不用打开 Visual Studio
app.ico 程序图标(可选),软件窗口左上角显示的小图片
aisound.dll 语音引擎核心文件(需自行准备,放同目录)
build.bat 是什么?
就是一个批处理脚本。平时编译需要打开"开发人员命令提示符"再输命令,有了它双击就能自动编译成 exe,省时间。

二、能学到什么

所有这些功能,一个代码文件就搞定了。

三、语音角色列表

编号标识符名称语言
01BabyXuBaby Xu普通话
02DaLong大龙粤语
03DonaldDuck唐老鸭普通话
04DuoXu多旭普通话
05JiuXu九旭普通话
06XiaoFeng小风普通话
07XiaoMei小美粤语
08XiaoPing小平普通话
09YanPing燕平普通话

四、DLL 函数接口

1. 初始化与终止

// 初始化语音引擎 bool aisound_initialize(); // 终止语音引擎,清理资源 void aisound_terminate();

2. 配置函数

// 配置语音引擎参数 // key: 配置项名称, value: 配置值 bool aisound_configure(const char* key, const char* value);

3. 语音合成控制

// 语音合成与播放 // text: 要合成的文本, user_data: 用户数据(可为 NULL) bool aisound_speak(const char* text, void* user_data); // 取消当前语音合成 bool aisound_cancel();

五、调用顺序

第 1 步:aisound_initialize() — 初始化引擎
第 2 步:aisound_configure("voice", "YanPing") — 配置语音角色
第 3 步:aisound_speak("你好", NULL) — 播放语音
第 4 步(可选):aisound_cancel() — 停止播放
第 5 步:aisound_terminate() — 清理资源

六、核心代码示例

6.1 声明 DLL 函数(P/Invoke)

using System; using System.Runtime.InteropServices; class 语音接口 { // 加载 aisound.dll,使用 Cdecl 调用约定 [DllImport("aisound.dll", CallingConvention = CallingConvention.Cdecl)] private static extern bool aisound_initialize(); [DllImport("aisound.dll", CallingConvention = CallingConvention.Cdecl)] private static extern bool aisound_configure(string key, string value); [DllImport("aisound.dll", CallingConvention = CallingConvention.Cdecl)] private static extern bool aisound_speak(string text, IntPtr userData); [DllImport("aisound.dll", CallingConvention = CallingConvention.Cdecl)] private static extern bool aisound_cancel(); [DllImport("aisound.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void aisound_terminate(); }

6.2 初始化和播放

// 初始化 if (aisound_initialize()) { // 设置语音角色为燕平 aisound_configure("voice", "YanPing"); // 播放文本 aisound_speak("你好,世界!", IntPtr.Zero); } // 程序结束时清理 aisound_terminate();

6.3 切换语音角色

// 设置为粤语 aisound_configure("voice", "DaLong"); // 设置为唐老鸭 aisound_configure("voice", "DonaldDuck");

七、build.bat 编译脚本

不用打开 Visual Studio,双击 build.bat 就能编译:

@echo off csc /target:winexe /out:AiSoundDemo.exe "C#调用例子aisound.cs" if %errorlevel% == 0 ( echo 编译成功! pause AiSoundDemo.exe ) else ( echo 编译失败! pause )
说明:csc 是 C# 编译器,/target:winexe 表示生成 Windows 窗体程序(不是控制台)。

八、注意事项