1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9 using Baidu.Aip.Speech;
10 using System.IO;
11 using Microsoft.DirectX;
12 using Microsoft.DirectX.DirectSound;
13
14 namespace DQ
15 {
16 public partial class Form_main : Form
17 {
18 public Form_main()
19 {
20 InitializeComponent();
21 }
22 private Asr _asrClient;
23 private Tts _ttsClient;
24 private SoundRecord sound;
25 private SoundPlay soundP;
26 private string time;
27 private string Rword;
28
29 private void Form_main_Load(object sender, EventArgs e)
30 {
31 // 设置APPID/AK/SK
32 var APP_ID = "10974923";
33 var API_KEY = "API_KEY";
34 var SECRET_KEY = "SECRET_KEY";
35 _asrClient = new Asr(API_KEY, SECRET_KEY);
36 _ttsClient = new Tts(API_KEY, SECRET_KEY);
37 }
38
39
40 private void btn_say_Click(object sender, EventArgs e)
41 {
42 time = DateTime.Now.ToString("yyyyMMddHHmmss");
43 sound = new SoundRecord();
44 sound.SetFileName(time + ".wav");//保存的文件名
45 sound.RecStart();//录制开始
46 btn_say.Enabled = false;
47 }
48
49 private void btn_stop_Click(object sender, EventArgs e)
50 {
51 sound.RecStop();//录制结束
52 btn_say.Enabled = true;
53 }
54
55 private void btn_send_Click(object sender, EventArgs e)
56 {
57 AsrData();
58 }
59 // 识别本地文件
60 public void AsrData()
61 {
62 var data = File.ReadAllBytes(time + ".wav");//获取文件字节数据
63 var result = _asrClient.Recognize(data, "pcm", 16000);
64 string Sresult = result.ToString();
65 int i = Sresult.IndexOf('[') + 8;
66 int j = Sresult.IndexOf(']') - 8;
67 Rword = Sresult.Substring(i, j - i);
68 listBox_result.Items.Add(Rword);
69 }
70
71 // 识别URL中的语音文件
72 public void AsrUrl()
73 {
74 var result = _asrClient.Recoginze(
75 "http://xxx.com/待识别的pcm文件地址",
76 "http://xxx.com/识别结果回调地址",
77 "pcm",
78 16000);
79 Console.WriteLine(result);
80 }
81
82 // 合成
83 public void Tts(string Tword)
84 {
85 // 可选参数
86 var option = new Dictionary<string, object>()
87 {
88 { "spd", 5}, // 语速
89 { "vol", 7}, // 音量
90 { "per", 4} // 发音人,4:情感度丫丫童声
91 };
92 var result = _ttsClient.Synthesis(Tword, option);
93
94 if (result.ErrorCode == 0) // 或 result.Success
95 {
96
97 string tts_name = "tts_" + time + ".mp3";
98 File.WriteAllBytes(tts_name, result.Data);
99
100 soundP.SoundPlay_mp3(tts_name);
101 }
102
103 }
104
105 private void btn_play_Click(object sender, EventArgs e)
106 {
107
108 soundP = new SoundPlay();
109 soundP.SoundPlay_mp3("tts.mp3");
110
111 // textBox_send.Text = result.ToString();
112 //Tts("明月几时有");
113 }
114 }
115 }