语音播报
在Form窗体中实现语音播报
以下为实现类
using System;
using System.Collections.Generic;
using System.IO;
using System.Media;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
using System.Runtime.InteropServices;
namespace NetProgramTextEdit
{
public class TtsUtil
{
private const string TTS_TMP_PATH = "voice_tmp.mp3";
// 设置APPID/AK/SK
private string APP_ID = "你的ID";
private string API_KEY = "你的KEY";
private string SECRET_KEY = "你的密钥";
private Baidu.Aip.Speech.Tts client;
public TtsUtil()
{
client = new Baidu.Aip.Speech.Tts(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
}
public static uint SND_ASYNC = 0x0001;
public static uint SND_FILENAME = 0x00020000;
[DllImport("winmm.dll")]
public static extern uint mciSendString(string lpstrCommand, string lpstrReturnString, uint uReturnLength, uint hWndCallback);
public void TtsPlay(string text)
{
// 可选参数
var option = new Dictionary<string, object>(){
{"spd", 5}, // 语速
{"vol", 7}, // 音量
{"per", 4} // 发音人,4:情感度丫丫童声
};
var result = client.Synthesis(text, option);
if (result.ErrorCode == 0) // 或 result.Success
{
File.WriteAllBytes(TTS_TMP_PATH, result.Data);
try
{
mciSendString(@"close temp_music", " ", 0, 0);
mciSendString(@"open " + TTS_TMP_PATH + " alias temp_music", " ", 0, 0);
mciSendString(@"play temp_music", " ", 0, 0);
}
catch
{ }
finally
{
mciSendString("close media", "", 0, 0);
}
//Audio audio = new Audio(TTS_TMP_PATH);
//audio.Play();
}
}
}
}