AiSound 语音引擎
C# 零基础调用教程 | 单文件实现语音合成
重要:本项目为 32 位程序,编译和运行都需要使用 32 位环境。
一、项目文件
C#调用例子aisound.cs
主代码文件,单文件包含所有功能(DLL调用 + WinForm界面)
build.bat
编译脚本,双击一键生成 exe,不用打开 Visual Studio
app.ico
程序图标(可选),软件窗口左上角显示的小图片
aisound.dll
语音引擎核心文件(需自行准备,放同目录)
build.bat 是什么?
就是一个批处理脚本。平时编译需要打开"开发人员命令提示符"再输命令,有了它双击就能自动编译成 exe,省时间。
二、能学到什么
- C# 调用外部 DLL:语音初始化、朗读、暂停、恢复、停止、切换音色
- WinForm 界面开发:窗体、文本框、按钮、下拉框、图标加载
- 面向对象封装:独立语音接口类,逻辑清晰、易于维护
- 异常处理:图标加载、DLL 检测、错误捕获
- 完整程序结构:入口 Main、界面创建、资源释放、状态管理
所有这些功能,一个代码文件就搞定了。
三、语音角色列表
| 编号 | 标识符 | 名称 | 语言 |
| 01 | BabyXu | Baby Xu | 普通话 |
| 02 | DaLong | 大龙 | 粤语 |
| 03 | DonaldDuck | 唐老鸭 | 普通话 |
| 04 | DuoXu | 多旭 | 普通话 |
| 05 | JiuXu | 九旭 | 普通话 |
| 06 | XiaoFeng | 小风 | 普通话 |
| 07 | XiaoMei | 小美 | 粤语 |
| 08 | XiaoPing | 小平 | 普通话 |
| 09 | YanPing | 燕平 | 普通话 |
四、DLL 函数接口
1. 初始化与终止
bool aisound_initialize();
void aisound_terminate();
2. 配置函数
bool aisound_configure(const char* key, const char* value);
3. 语音合成控制
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 语音接口
{
[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 窗体程序(不是控制台)。
八、注意事项
- 所有函数返回 bool 类型,表示操作是否成功
- 必须按顺序调用:先初始化,再配置,最后使用
- 使用完成后必须调用 aisound_terminate() 释放资源
- 文本编码应为 UTF-8
- 第二个参数 user_data 在示例中传递 NULL(即 IntPtr.Zero)
- 必须使用 32 位编译环境,64 位会报错