mengjie лет назад: 8
Родитель
Сommit
f8fc8a8069

+ 367 - 0
codegit/CallCenterApi/CallCenterApi.Interface/CallCenterApi.Interface/Controllers/RecordsController.cs

@@ -0,0 +1,367 @@
1
+using Baidu.Aip.Speech;
2
+using CallCenterApi.DB;
3
+using CallCenterApi.Interface.Controllers.Base;
4
+using System;
5
+using System.Collections.Generic;
6
+using System.Data;
7
+using System.Diagnostics;
8
+using System.IO;
9
+using System.Linq;
10
+using System.Net;
11
+using System.Threading;
12
+using System.Web;
13
+using System.Web.Mvc;
14
+
15
+namespace CallCenterApi.Interface.Controllers
16
+{
17
+    public class RecordsController : BaseController
18
+    {
19
+        // GET: Records
20
+        public ActionResult Index()
21
+        {
22
+            return View();
23
+        }
24
+
25
+        //语音识别
26
+        private Asr _asrClient;//readonly
27
+        //语音合成
28
+        private Tts _ttsClient;//readonly
29
+        //验证身份参数
30
+        string strAK = "PuGGxl9vGrdijDTBYFBhEdVx";
31
+        string strSK = "aGmyOET05Os0atXBxFWXsC9qf1GgXv6R";
32
+        string backdata = "";
33
+
34
+        //public SpeechDemo()
35
+        //{
36
+        //    _asrClient = new Asr(strAK, strSK);
37
+        //    _ttsClient = new Tts("PuGGxl9vGrdijDTBYFBhEdVx", "aGmyOET05Os0atXBxFWXsC9qf1GgXv6R");
38
+        //}
39
+        string scallid = "453";
40
+        string sfilepath = "E:\\callrec\\luyin\\20170508\\1004\\453_1004_173534.mp3";
41
+        public ActionResult GetCallOutprefix(string callid, string filepath)
42
+        {
43
+            ActionResult res = NoToken("未知错误,请重新登录");
44
+            //if (Request.IsAuthenticated)
45
+            //{
46
+            callid = scallid;
47
+            filepath = sfilepath;
48
+            _asrClient = new Asr(strAK, strSK);
49
+            _ttsClient = new Tts("PuGGxl9vGrdijDTBYFBhEdVx", "aGmyOET05Os0atXBxFWXsC9qf1GgXv6R");
50
+            Init();//(callid, filepath);
51
+
52
+
53
+            res = Success("音频文件转换测试", backdata);
54
+            // }
55
+            return res;
56
+        }
57
+
58
+
59
+        public void Init()//(string callid, string filepath)
60
+        {
61
+            //通过读取配置文件,获取数据库
62
+
63
+            string dbpath = Environment.CurrentDirectory + @"\Config.ini";  //指定ini文件的路径
64
+            dbpath = "E:\\项目\\百度语音\\语音\\代码\\ASR_Speech\\ASR_Speech\\bin\\Debug\\Config.ini";
65
+            Common.IniFile ini = new Common.IniFile(dbpath);
66
+            string _dbset = ini.IniReadValue("基础设置SQL", "Catalog");
67
+            string _url = ini.IniReadValue("基础设置", "服务器地址");
68
+            //通过读取数据库,获得URL
69
+            DataTable dt_Recor = DbHelperSQL.Query("select FilePath,CallId from T_Call_CallRecords where IsTranslate is NULL or IsTranslate!=1 ").Tables[0];
70
+            //DataTable dt_Recor = Common.SQLHelper.QueryDataTable(_dbset, "select FilePath,CallId from T_Call_CallRecords where 1=1 ", CommandType.Text, null);
71
+            if (dt_Recor.Rows.Count > 0)
72
+            {
73
+                int i = 0;
74
+                foreach (DataRow dr in dt_Recor.Rows)
75
+                {
76
+                    //录音记录id
77
+                    string callid = dr[1].ToString();
78
+                    //录音记录URL路径
79
+                    string filepath = dr[0].ToString();
80
+                    if (!string.IsNullOrEmpty(filepath))
81
+                    {
82
+                        //通过cmd执行ffmpeg改变音频采样率
83
+                        Process p = new Process();
84
+                        p.StartInfo.FileName = "cmd.exe";
85
+                        p.StartInfo.UseShellExecute = false;
86
+                        p.StartInfo.RedirectStandardOutput = true;
87
+                        p.StartInfo.RedirectStandardInput = true;
88
+                        p.StartInfo.RedirectStandardError = true;
89
+                        p.StartInfo.CreateNoWindow = true;
90
+                        //p.StartInfo.Arguments = "ffmpeg -i "+fileName+ " -ar 16000 "+ namePart + "New.wav";//参数以空格分隔,如果某个参数为空,可以传入””
91
+
92
+                        //p.Start();
93
+                        ////先进入cmd命令
94
+                        ////再打开FFmpeg.exe
95
+                        string ffmpegLocation = System.Threading.Thread.GetDomain().BaseDirectory;// +"bin\\";
96
+                        ////p.StandardInput.WriteLine("exit");
97
+                        //p.StandardInput.WriteLine("cd d/ " + ffmpegLocation + "ffmpeg.exe");
98
+                        //p.StandardInput.WriteLine(ffmpegLocation.TrimEnd('\\'));
99
+
100
+                        //判断是否存在文件夹,不存在则创建
101
+                        string voices_path = ffmpegLocation + "temp_voices";
102
+                        if (!Directory.Exists(voices_path))
103
+                        {
104
+                            Directory.CreateDirectory(voices_path);
105
+                        }
106
+                        //filepath:E:\callrec\luyin\20170506\1200\4_1200_164414.mp3
107
+                        string[] filepaths = filepath.Split(new char[] { '\\' });
108
+                        //res_audiopath:http://192.168.5.7:88/callrec/luyin/20170506/1200/4_1200_164414.mp3
109
+                        string res_audiopath = filepath.Replace(filepath.Substring(0, 2), _url).Replace("mp3", "wav").Replace(@"\", @"/");
110
+                        //voices_path:D:\项目\XFTest_WITHDB\XFTest\bin\Debug
111
+                        //namePart:D:\项目\XFTest_WITHDB\XFTest\bin\Debug\temp_voices\4_1200_164414.wav
112
+                        string namePart = voices_path + @"\" + filepaths.Last().Replace("mp3", "wav");
113
+                        //pcm和WAV格式文件可以解析出来
114
+                        //this.AsrData(p, ffmpegLocation, res_audiopath, callid, namePart);
115
+                        //20171013 用本地文件测试
116
+                        //this.AsrData(p, ffmpegLocation, ffmpegLocation + "0.mp3", callid, namePart);
117
+                        //20171016
118
+                        this.AsrData(p, ffmpegLocation, "http://192.168.5.7:88/CallREC/luyin/20170908/1/427_1_141423.wav", callid, namePart);
119
+                    }
120
+                }
121
+            }
122
+        }
123
+        /// <summary>
124
+        /// 识别本地文件
125
+        /// </summary>
126
+        public void AsrData(Process p, string filelocation, string filepath, string callid, string namepart)
127
+        {
128
+            #region 读取本地文件
129
+            //int audiocounts = SplitAudio(filepath);
130
+
131
+            ////读取结果
132
+            //string rec_result = string.Empty;
133
+
134
+            ////WebClient _wClient = new WebClient();
135
+            ////byte[] p_pcm = _wClient.DownloadData("http://192.168.5.7:88/CallREC/luyin/20170508/1004/453_1004_173534.mp3");
136
+
137
+            ////读取远端文件是否存在
138
+            ////if (!RemoteFileExists("http://192.168.5.7:88/CallREC/luyin/20170908/1/427_1_141423.wav"))
139
+            ////    return;
140
+            ////ffmpeg -i http://192.168.5.7:88/callrec/luyin/20170506/1200/4_1200_164414.mp3 -f wav -ar 16000 -ac 1 -ab 16 D:\项目\XFTest_WITHDB\XFTest\bin\Debug\temp_voices\4_1200_164414.wav
141
+
142
+            //string temp_filename = filepath.Split('\\').Last().Split('.')[0] + "_temp_";
143
+            //Console.Write("\n开始语音听写 ...\n");
144
+            //for (int i = 0; i < audiocounts; i++)
145
+            //{
146
+            //    p.Start();
147
+            //    //先进入cmd命令
148
+            //    //再打开FFmpeg.exe
149
+
150
+            //    //p.StandardInput.WriteLine("exit");
151
+            //    p.StandardInput.WriteLine("cd d/ " + filelocation + "ffmpeg.exe");
152
+            //    p.StandardInput.WriteLine(filelocation.TrimEnd('\\'));
153
+
154
+            //    //p.StandardInput.WriteLine("ffmpeg -i " + temp_filename + i + ".mp3 -f pcm -ar 16000 -ac 1 -ab 16 " + namepart.Replace(@"/", @"\"));
155
+            //    string changefile = "ffmpeg -i " + filelocation + temp_filename + i + ".mp3 -f wav -ar 16000 -ac 1 -ab 16 " + filelocation + temp_filename + i + ".wav";
156
+
157
+            //    p.StandardInput.WriteLine(changefile);
158
+            //    Thread.Sleep(3000);
159
+            //    p.StandardInput.WriteLine("exit");
160
+            //    //Kill 是终止没有图形化界面的进程的唯一方法。
161
+            //    p.Kill();
162
+            //    //此处可以返回一个字符串,此例是返回压缩成功之后的一个文件路径
163
+            //    var data = File.ReadAllBytes(filelocation + temp_filename + i + ".wav");
164
+            //    var result_Json = _asrClient.Recognize(data, "wav", 16000);
165
+            //    if (rec_result != null)
166
+            //    {
167
+            //        int _code = int.Parse(result_Json["err_no"].ToString());
168
+            //        if (_code == 0)
169
+            //        {
170
+            //            string _res = result_Json["result"].ToString();
171
+            //            rec_result += _res.TrimStart('[').TrimEnd(']');
172
+            //        }
173
+            //        else
174
+            //        {
175
+            //            string _msg = result_Json["err_msg"].ToString();
176
+            //            rec_result += _msg;
177
+            //        }
178
+            //    }
179
+            //}
180
+
181
+            //Console.Write("\n语音听写结束\n");
182
+            //Console.Write("=============================================================\n");
183
+            //Console.Write(rec_result);
184
+            //Console.Write("\n=============================================================\n");
185
+            //int exe_res = Common.SQLHelper.Execute("XTZHSW_copy", "update T_Call_CallRecords set OperateObject='1',Remark='" + rec_result + "' where CallId='" + callid + "'", CommandType.Text, null);
186
+            //if (exe_res > 0)
187
+            //{
188
+            //    Console.WriteLine("\n数据库更新成功\n");
189
+            //    //操作完删除转换后的文件
190
+            //    if (File.Exists(filelocation + namepart.Replace(@"/", @"\")))
191
+            //    {
192
+            //        File.Delete(filelocation + namepart.Replace(@"/", @"\"));
193
+            //    }
194
+            //}
195
+            #endregion
196
+
197
+            #region 读取URL中的文件
198
+            //读取结果
199
+            string rec_result = string.Empty;
200
+            //读取远端文件是否存在
201
+            if (!RemoteFileExists(filepath))
202
+                return;
203
+            int audiocounts = SplitAudio(filepath);
204
+            string temp_filename = filepath.Split('/').Last().Split('.')[0] + "_temp_";
205
+            Console.Write("\n开始语音听写 ...\n");
206
+            for (int i = 0; i < audiocounts; i++)
207
+            {
208
+                p.Start();
209
+                //先进入cmd命令
210
+                //再打开FFmpeg.exe
211
+
212
+                //p.StandardInput.WriteLine("exit");
213
+                p.StandardInput.WriteLine("cd d/ " + filelocation + "ffmpeg.exe");
214
+                p.StandardInput.WriteLine(filelocation.TrimEnd('\\'));
215
+
216
+                //p.StandardInput.WriteLine("ffmpeg -i " + temp_filename + i + ".mp3 -f pcm -ar 16000 -ac 1 -ab 16 " + namepart.Replace(@"/", @"\"));
217
+                string changefile = "ffmpeg -i " + filelocation + temp_filename + i + ".wav -acodec pcm_s16le -f s16le -ar 16000 -ac 1 " + filelocation + temp_filename + i + ".pcm";
218
+
219
+                p.StandardInput.WriteLine(changefile);
220
+                Thread.Sleep(3000);
221
+                p.StandardInput.WriteLine("exit");
222
+                //Kill 是终止没有图形化界面的进程的唯一方法。
223
+                //p.Kill();
224
+                //此处可以返回一个字符串,此例是返回压缩成功之后的一个文件路径
225
+                var data = System.IO.File.ReadAllBytes(filelocation + temp_filename + i + ".pcm");
226
+                var result_Json = _asrClient.Recognize(data, "pcm", 16000);
227
+                if (rec_result != null)
228
+                {
229
+                    int _code = int.Parse(result_Json["err_no"].ToString());
230
+                    if (_code == 0)
231
+                    {
232
+                        string _res = result_Json["result"].ToString();
233
+                        rec_result += _res.TrimStart('[').TrimEnd(']');
234
+                    }
235
+                    else
236
+                    {
237
+                        string _msg = result_Json["err_msg"].ToString();
238
+                        rec_result += _msg;
239
+                    }
240
+                }
241
+            }
242
+            backdata = rec_result;
243
+            //Console.Write("\n语音听写结束\n");
244
+            //Console.Write("=============================================================\n");
245
+            //Console.Write(rec_result);
246
+            //Console.Write("\n=============================================================\n");
247
+            int exe_res = DbHelperSQL.ExecuteSql("update T_Call_CallRecords set IsTranslate=1,RecordsContent='" + rec_result + "' where CallId='" + callid + "'");
248
+            if (exe_res > 0)
249
+            {
250
+                //Console.WriteLine("\n数据库更新成功\n");
251
+                //操作完删除转换后的文件
252
+                string x = namepart.Replace(@"/", @"\");
253
+                if (System.IO.File.Exists(filelocation + namepart.Replace(@"/", @"\")))
254
+                {
255
+                    System.IO.File.Delete(filelocation + namepart.Replace(@"/", @"\"));
256
+                }
257
+            }
258
+            #endregion
259
+        }
260
+
261
+        /// <summary>
262
+        /// 分割音频
263
+        /// </summary>
264
+        /// <param name="filepath">音频路径</param>
265
+        private int SplitAudio(string filepath)
266
+        {
267
+            //获取音频时长
268
+            string length = "";
269
+            string[] sumlength;
270
+            int sec = 0;
271
+            DateTime beginTime = DateTime.Parse("00:00:00");
272
+            int index = 1;
273
+            using (Process pro = new Process())
274
+            {
275
+                pro.StartInfo.UseShellExecute = false;
276
+                pro.StartInfo.ErrorDialog = false;
277
+                pro.StartInfo.RedirectStandardError = true;
278
+
279
+                pro.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "bin\\ffmpeg.exe";
280
+                pro.StartInfo.Arguments = " -i " + filepath;
281
+
282
+                pro.Start();
283
+                StreamReader errorreader = pro.StandardError;
284
+                pro.WaitForExit(1000);
285
+
286
+                string result = errorreader.ReadToEnd();
287
+                if (!string.IsNullOrEmpty(result))
288
+                {
289
+                    result = result.Substring(result.IndexOf("Duration: ") + ("Duration: ").Length, ("00:00:00").Length);
290
+                    //result = "00:01:16";
291
+                    length = result;
292
+                    sumlength = length.Split(':');
293
+                    sec += (int.Parse(sumlength[0].ToString()) * 60 * 60 + int.Parse(sumlength[1].ToString()) * 60 + int.Parse(sumlength[2].ToString()));
294
+                }
295
+            }
296
+            //对音频进行分割
297
+            //ffmpeg -ss 00:00:00 -i input.mp4 -c copy -t 60 output.mp4
298
+            if (sec > 30)
299
+            {
300
+                Process p = new Process();
301
+                p.StartInfo.FileName = "cmd.exe";
302
+                p.StartInfo.UseShellExecute = false;
303
+                p.StartInfo.RedirectStandardOutput = true;
304
+                p.StartInfo.RedirectStandardInput = true;
305
+                p.StartInfo.RedirectStandardError = true;
306
+                // p.StartInfo.CreateNoWindow = true;
307
+                p.Start();
308
+                string ffmpegLocation = System.Threading.Thread.GetDomain().BaseDirectory + "bin\\";
309
+                p.StandardInput.WriteLine("exit");
310
+                p.StandardInput.WriteLine("cd d/ " + ffmpegLocation + "ffmpeg.exe");
311
+                p.StandardInput.WriteLine(ffmpegLocation.TrimEnd('\\'));
312
+                string fileName = System.IO.Path.GetFileName(filepath).Split('.')[0];
313
+                index = sec / 28 + 1;
314
+
315
+                for (int i = 0; i < index; i++)
316
+                {
317
+                    string splitstr = "ffmpeg -i " + filepath + " -ss " + beginTime.ToLongTimeString() + " -t 28 -acodec copy " + ffmpegLocation + fileName + "_temp_" + i + "." + System.IO.Path.GetFileName(filepath).Split('.')[1];
318
+                    p.StandardInput.WriteLine(splitstr);
319
+                    beginTime = beginTime.AddSeconds(29);
320
+                    Thread.Sleep(3000);
321
+                }
322
+                p.StandardInput.WriteLine("exit");
323
+                //Kill 是终止没有图形化界面的进程的唯一方法。
324
+                //p.Kill();
325
+            }
326
+            return index;
327
+        }
328
+
329
+        /// <summary>  
330
+        /// 判断远程文件是否存在  
331
+        /// </summary>  
332
+        /// <param name="fileUrl"></param>  
333
+        /// <returns></returns>  
334
+        public static bool RemoteFileExists(string fileUrl)
335
+        {
336
+            HttpWebRequest re = null;
337
+            HttpWebResponse res = null;
338
+            try
339
+            {
340
+                re = (HttpWebRequest)WebRequest.Create(fileUrl);
341
+                res = (HttpWebResponse)re.GetResponse();
342
+                if (res.ContentLength != 0)
343
+                {
344
+                    //MessageBox.Show("文件存在");  
345
+                    return true;
346
+                }
347
+            }
348
+            catch (Exception)
349
+            {
350
+                //MessageBox.Show("无此文件");  
351
+                return false;
352
+            }
353
+            finally
354
+            {
355
+                if (re != null)
356
+                {
357
+                    re.Abort();//销毁关闭连接  
358
+                }
359
+                if (res != null)
360
+                {
361
+                    res.Close();//销毁关闭响应  
362
+                }
363
+            }
364
+            return false;
365
+        }
366
+    }
367
+}

BIN
codegit/CallCenterApi/CallCenterApi.Interface/CallCenterApi.Interface/bin/Interop.Shell32.dll


BIN
codegit/CallCenterApi/CallCenterApi.Interface/CallCenterApi.Interface/obj/Debug/Interop.Shell32.dll