/// <summary> /// 截取音频后,对每个小音频获语音转文字 /// </summary> /// <param name="startMilliSecond">开始时间戳</param> /// <param name="endMilliSecond">结束时间戳</param> /// <param name="reader">音频流</param> /// <param name="i">用于创建新的文件</param> /// <param name="language">语言(zh,en)</param> /// <param name="splitTime">时间间隔</param> private void GetBaiduSpeech1(TimeSpan startMilliSecond, TimeSpan endMilliSecond, string sound_path, int i, string language, double splitTime) { try { var reader = new AudioFileReader(sound_path); //开始时间往前取startMilliSecond一半的偏移,结束时间往后取间隔时间的一半的偏移 if (i == 0) { startMilliSecond = startMilliSecond - TimeSpan.FromMilliseconds(startMilliSecond.TotalMilliseconds / 2); } else { startMilliSecond = startMilliSecond - TimeSpan.FromMilliseconds(splitTime / 2); } if (endMilliSecond < reader.TotalTime)//最后一次不用取偏移 { endMilliSecond = endMilliSecond + TimeSpan.FromMilliseconds(splitTime / 2); } TimeSpan span = endMilliSecond - startMilliSecond; if (span.TotalSeconds > 60)//超过60s,只取60秒 { span = TimeSpan.FromSeconds(60); } var trimed = reader.Skip(startMilliSecond).Take(endMilliSecond - startMilliSecond); //保存新的音频文件 string fileName = Path.GetFileNameWithoutExtension(sound_path) + "_" + i + Path.GetExtension(sound_path);//重命名文件 string newFolder = System.AppDomain.CurrentDomain.BaseDirectory + "NewSoundFiles/" + Path.GetFileNameWithoutExtension(sound_path) + "/"; //重新存储到一个新的文件目录 if (!System.IO.Directory.Exists(newFolder)) { System.IO.Directory.CreateDirectory(newFolder); } string newFile = newFolder + fileName; WaveFileWriter.CreateWaveFile16(newFile, trimed); //绝对路径 string path_absolute = context.Server.MapPath("/NewSoundFiles/" + Path.GetFileNameWithoutExtension(sound_path) + "/" + fileName); voiceFiles.Add(UploadFile.PostFile(path_absolute)); if (span == TimeSpan.FromSeconds(60))//音频大于60s { //小音频 var _reader = new AudioFileReader(sound_path); var _trimed = _reader.Skip(startMilliSecond).Take(span); //保存新的音频文件 string _fileName = "_" + Path.GetFileNameWithoutExtension(sound_path) + "_" + i + Path.GetExtension(sound_path);//重命名文件 string _newFile = newFolder + _fileName; WaveFileWriter.CreateWaveFile16(_newFile, _trimed); baidu_text.Add(BaiduSpeech.BaiduTranslateToText(_newFile, language, _trimed.WaveFormat.SampleRate.ToString())); } else { baidu_text.Add(BaiduSpeech.BaiduTranslateToText(newFile, language, trimed.WaveFormat.SampleRate.ToString())); } reader.Close(); reader.Dispose(); } catch (Exception ex) { LogHelper.Error(ex.Message); } }
/// <summary> /// 截取音频后,对每个小音频获语音转文字,一个音频对应一段文字 /// </summary> /// <param name="startMilliSecond"></param> /// <param name="endMilliSecond"></param> /// <param name="reader"></param> /// <param name="sound_path"></param> /// <param name="_name"></param> /// <param name="language"></param> /// <param name="splitTime"></param> private void GetBaiduSpeech(TimeSpan startMilliSecond, TimeSpan endMilliSecond, string sound_path, int i, string language, double splitTime) { string newFile = ""; string _newFile = ""; string pcm_newFile = ""; bool need_delete = true; //将文件保存到新的文件夹(sound_path是原音频路径,newFolder是新的小音频路径,使用完成后将上传到服务器成功的音频删除) string newFolder = System.AppDomain.CurrentDomain.BaseDirectory + "NewSoundFiles/" + Path.GetFileNameWithoutExtension(sound_path) + "/"; newFolder = newFolder.Replace("/", "\\"); AudioFileReader reader = new AudioFileReader(sound_path); AudioFileReader _reader = null;//超过60s音频截取小音频 try { #region 为截取音频做准备 //开始时间往前取startMilliSecond一半的偏移,结束时间往后取间隔时间的一半的偏移 if (i == 0) { startMilliSecond = startMilliSecond - TimeSpan.FromMilliseconds(startMilliSecond.TotalMilliseconds / 2); } else { startMilliSecond = startMilliSecond - TimeSpan.FromMilliseconds(splitTime / 2); } if (endMilliSecond < reader.TotalTime)//最后一次不用取偏移 { endMilliSecond = endMilliSecond + TimeSpan.FromMilliseconds(splitTime / 2); } TimeSpan span = endMilliSecond - startMilliSecond; if (span.TotalSeconds > 60)//超过60s,只取50秒 { span = TimeSpan.FromSeconds(50); } var trimed = reader.Skip(startMilliSecond).Take(endMilliSecond - startMilliSecond); #endregion string fileName = Path.GetFileNameWithoutExtension(sound_path) + "_" + i + Path.GetExtension(sound_path);//重命名文件 //重新存储到一个新的文件目录 if (!System.IO.Directory.Exists(newFolder)) { System.IO.Directory.CreateDirectory(newFolder); } //拼接后的文件路径 newFile = newFolder + fileName; //截取小音频文件 WaveFileWriter.CreateWaveFile16(newFile, trimed); //上传到文件服务器 string server_path = UploadFile.PostFile(newFile); if (Util.isNotNull(server_path)) { //上传成功 voiceFiles.Add(server_path); } else { need_delete = false; //上传失败,在服务器上的路径 voiceFiles.Add(Util.getServerPath() + "/NewSoundFiles/" + Path.GetFileNameWithoutExtension(sound_path) + "/" + fileName); } //大于60s的需要再处理 if (span == TimeSpan.FromSeconds(50))//音频大于60s,只截取50s { //小音频 _reader = new AudioFileReader(sound_path); var _trimed = _reader.Skip(startMilliSecond).Take(span); //保存新的音频文件 string _fileName = "_" + Path.GetFileNameWithoutExtension(sound_path) + "_" + i + ".pcm";//重命名文件 _newFile = newFolder + _fileName; WaveFileWriter.CreateWaveFile16(_newFile, _trimed); //将音频转换为文字 //baidu_text.Add(BaiduSpeech.BaiduTranslateToText(_newFile, language, _trimed.WaveFormat.SampleRate.ToString())); baidu_text.Add(Rays.Utility.BadiAI.BaiduAI.BaiduTranslateToText(_newFile, language, trimed.WaveFormat.SampleRate.ToString())); } else { //将wav转换成pcm可以提高识别速度 pcm_newFile = NAudioHelper.GetPcmPath(newFile); //将音频转换为文字 //baidu_text.Add(BaiduSpeech.BaiduTranslateToText(pcm_newFile, language, trimed.WaveFormat.SampleRate.ToString())); baidu_text.Add(Rays.Utility.BadiAI.BaiduAI.BaiduTranslateToText(pcm_newFile, language, trimed.WaveFormat.SampleRate.ToString())); } } catch (Exception ex) { LogHelper.Error("GetBaiduSpeech:" + ex.Message); } finally { reader.Close(); reader.Dispose(); if (_reader != null) { _reader.Close(); _reader.Dispose(); } //删除文件 //if (File.Exists(_newFile)) //{ // File.Delete(_newFile); //} //if (need_delete) //{ // if (File.Exists(newFile)) // { // File.Delete(newFile); // } //} ////删除目录 //if (Directory.Exists(newFolder) && Directory.GetFiles(newFolder).Length == 0) //{ // Directory.Delete(newFolder); //} //if (File.Exists(pcm_newFile)) //{ // File.Delete(pcm_newFile); // string pcm_folder = Path.GetDirectoryName(pcm_newFile); // //删除目录 // if (Directory.Exists(pcm_folder) && Directory.GetFiles(pcm_folder).Length == 0) // { // Directory.Delete(pcm_folder); // } //} } }
/// <summary> /// 解析音频文件,获取时间戳,截取音频,语音转文字 /// </summary> /// <param name="sound_path"></param> /// <param name="word_path"></param> /// <param name="language"></param> /// <param name="splitTime"></param> public void GetTimeSpanLrc(string sound_path, string word_path, string language, double splitTime = 1.5) { string sound_path_mp3 = ""; //音频格式转换后的文件 List <string> cut_sound_files = new List <string> (); //切分后的音频文件 string folder = Path.GetDirectoryName(sound_path); try { if (sound_path.ToLower().EndsWith(".mp3")) { sound_path_mp3 = sound_path; //通过NAudio将文件转换为WAV格式,返回新的文件路径 sound_path = NAudioHelper.GetWavPath(sound_path); } //音频处理,通过lrc的时间戳来截取音频与内容 //1.先从lrc里面获取时间戳与内容 if (Path.GetExtension(word_path).Contains("lrc")) { Dictionary <TimeSpan, string> lrcs = Util.ReadLrc(word_path); List <TimeSpan> times = lrcs.Keys.ToList(); for (int i = 0; i < times.Count; i++) { TextContrastResult _result = new TextContrastResult(); //2.通过时间戳,截取音频 string cut_sound_file = folder + "\\" + i + "_" + sys.getRandomStr() + Path.GetExtension(sound_path); TimeSpan _start = new TimeSpan(); TimeSpan _end = new TimeSpan(); if (i == times.Count - 1) { _end = TimeSpan.Parse(FfmpegHelper.getMediaDuration(sound_path)); } else { _end = times[i + 1]; } _start = times[i]; _result.timespan = times[i].TotalSeconds; _result.contractText = lrcs[times[i]]; _result.baiduText = lrcs[times[i]]; _result.precent = "100%"; bool is_success = FfmpegHelper.CutAudioFile(sound_path, cut_sound_file, _start, _end - _start); if (is_success) { cut_sound_files.Add(cut_sound_file); } //上传到服务器 if (File.Exists(cut_sound_file)) { string server_path = UploadFile.PostFile(cut_sound_file); _result.file_url = server_path; } results.Add(_result); } } //原文 string _originalText = Util.ReadTxt(word_path); originalText = string.Join("", _originalText.Split('|')); } catch (Exception ex) { LogHelper.Error(ex.Message); } finally { isFinish = true; //删除切分的文件 foreach (string cut_sound_file in cut_sound_files) { if (Util.isNotNull(cut_sound_file) && File.Exists(cut_sound_file)) { File.Delete(cut_sound_file); } } //删除MP3文件 if (Util.isNotNull(sound_path_mp3) && File.Exists(sound_path_mp3)) { File.Delete(sound_path_mp3); string mp3_folder = Path.GetDirectoryName(sound_path_mp3); if (Directory.Exists(mp3_folder) && Directory.GetFiles(mp3_folder).Length == 0) { Directory.Delete(mp3_folder); } } //删除word文件 if (File.Exists(word_path)) { File.Delete(word_path); //删除word文件目录 string word_folder = Path.GetDirectoryName(word_path); if (Directory.Exists(word_folder) && Directory.GetFiles(word_folder).Length == 0) { Directory.Delete(word_folder); } } //删除文件夹,删除原音频文件 if (File.Exists(sound_path)) { File.Delete(sound_path); //删除原音频目录 string sound_folder = Path.GetDirectoryName(sound_path); if (Directory.Exists(sound_folder) && Directory.GetFiles(sound_folder).Length == 0) { Directory.Delete(sound_folder); } } } }
/// <summary> /// 音频合成(要注意音频顺序,只支持MP3格式) /// </summary> /// <param name="data"> /// [{"mp3":"xxxxxxxxx","topsize":0},{"mp3":"xxxxxxxxx","topsize":1},{"mp3":"xxxxxxxxx","topsize":2} /// ,{"mp3":"xxxxxxxxx","topsize":3},{"mp3":"xxxxxxxxx","topsize":4}] /// </param> /// <returns></returns> public ApiResult ComposeAudios(dynamic data) { ApiResult apiResult = new ApiResult(); List <string> local_mp3_list = new List <string>(); string output = ""; try { if (!Util.isNotNull(data)) { return(new Models.ApiResult() { success = false, message = "参数错误" }); } string folder = System.AppDomain.CurrentDomain.BaseDirectory + "download/"; //获取formdata数据 if (!System.IO.Directory.Exists(Path.GetDirectoryName(folder))) { System.IO.Directory.CreateDirectory(Path.GetDirectoryName(folder)); } var _mp3 = new { mp3 = "", topsize = 0 }; List <dynamic> list = new List <dynamic>(); list.Add(_mp3); dynamic[] _mp3_data_list = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(data.ToString(), list.ToArray()); var mp3_list = _mp3_data_list.OrderBy(o => o.topsize).Select(o => o.mp3); string file_type = ""; foreach (var mp3 in mp3_list) { string mp3_file = mp3.ToString(); if (!Path.GetExtension(mp3_file).ToLower().Contains("mp3")) { return(new ApiResult() { success = false, message = "只支持MP3格式的文件拼接" }); } file_type = Path.GetExtension(mp3.ToString()); string save_path = folder + Path.GetFileName(mp3.ToString()); string local_mp3 = UploadFile.DownloadFile(save_path.Replace("/", "\\"), mp3.ToString()).Result; local_mp3_list.Add(local_mp3); } output = folder + sys.getRandomStr() + "_output" + file_type; if (FfmpegHelper.ComposeAudios(local_mp3_list.ToArray(), ref output)) { apiResult.data = UploadFile.PostFile(output); apiResult.success = true; apiResult.message = "合成成功"; } else { return(new ApiResult() { success = false, message = "合成失败" }); } } catch (Exception ex) { return(new ApiResult() { success = false, message = ex.Message }); } finally { if (local_mp3_list.Count > 0) { foreach (string mp3 in local_mp3_list) { File.Delete(mp3); } } if (Util.isNotNull(output)) { File.Delete(output); } } return(apiResult); }
public ApiResult speechEvaluation() { ApiResult apiResult = new ApiResult(); string speechFilePath = string.Empty; string silkFile = string.Empty; string otherFile = string.Empty; try { string fileName = sys.getRandomStr();//用作最终生成的文件名 List <string> speechResult = null; //接受小程序提交过来的录音文件 System.Web.HttpFileCollection fileList = HttpContext.Current.Request.Files; string enText = HttpContext.Current.Request.Form["enText"]; string lan = HttpContext.Current.Request.Form["language"]; enText = enText.Replace("\n", "").Replace("\r", ""); if (fileList.Count < 1) { return(new ApiResult() { success = false, message = "语音文件为空" }); } System.Web.HttpPostedFile file = fileList[0]; //判断文件是silk格式还是webm格式,不能通过文件后缀判断 StreamReader reader = new StreamReader(file.InputStream); string fileString = reader.ReadToEnd(); BaiduAI ai = new BaiduAI(); if (fileString.IndexOf("SILK_V3") > -1) { //silk格式文件 silkFile = CommonServices.createFileFullPath("silk"); file.SaveAs(silkFile); speechFilePath = CmdServices.silk2wav(silkFile); string fileType = CommonServices.getFileType(speechFilePath); //speechResult = ai.AsrData(speechFilePath, fileType, 16000, lan); FileInfo file_info = new FileInfo(speechFilePath); speechResult = Util.GetSpeechResult(file_info, lan); } else if (fileString.IndexOf("webm") > -1) { #region //webm格式文件 //微信小程序webm格式录音文件,data:audio/webm;base64,GkXfo59ChoEBQv... //1.去掉data:audio/webm;base64, //2.对GkXfo59ChoEBQv...字符串解码为webm文件 //3.webm文件转wav文件 #endregion LogHelper.Info("小程序音频评分开始:" + DateTime.Now); fileString = fileString.Substring(fileString.IndexOf(',') + 1); byte[] bytes = Convert.FromBase64String(fileString); string webmFile = CommonServices.createFileFullPath("webm"); using (FileStream fs = new FileStream(webmFile, FileMode.Create, FileAccess.Write)) { fs.Write(bytes, 0, bytes.Length); fs.Flush(); } speechFilePath = CmdServices.webm2wav(webmFile); string fileType = CommonServices.getFileType(speechFilePath); //speechResult = ai.AsrData(speechFilePath, fileType, 16000, lan); LogHelper.Info("小程序音频评分结束:" + DateTime.Now); FileInfo file_info = new FileInfo(speechFilePath); speechResult = Util.GetSpeechResult(file_info, lan); } else//mp3或者wav,如果不是16000HZ,16bit,单声道,都转格式 { string fileType = CommonServices.getFileType(file.FileName); otherFile = CommonServices.createFileFullPath(fileType); file.SaveAs(otherFile); //转换成wav\ LogHelper.Info("MP3转wav"); string mp3_folder = HttpContext.Current.Server.MapPath("/upload/") + sys.getDateStr() + "\\"; if (Directory.Exists(mp3_folder)) { Directory.CreateDirectory(mp3_folder); } speechFilePath = mp3_folder + sys.getRandomStr() + ".wav"; //speechFilePath = CmdServices.mp32wav(otherFile); FfmpegHelper.ChangeFileType(otherFile, speechFilePath); LogHelper.Info("百度转语音开始"); //speechResult = ai.AsrData(speechFilePath, CommonServices.getFileType(speechFilePath), 16000, lan); FileInfo file_info = new FileInfo(speechFilePath); speechResult = Util.GetSpeechResult(file_info, lan); } string duration = FileServices.getMediaDuration(speechFilePath); int seconds = SppechEvaluation.timeToSecond(duration); //评分 int totalSocre = 0; int accuracySocre = 0; int fluencySocre = 0; int integritySocre = 0; int tempScore = 0; string sentence = ""; //LogHelper.Info("百度转语音完成,准备计算分数。seconds:" + seconds+";count:"+ speechResult.Count); if (speechResult == null) { sentence = SppechEvaluation.getSentenceAccuracy3(enText, speechResult); apiResult.data = new { totalSocre, accuracySocre, fluencySocre, integritySocre, speechFilePath = UploadFile.PostFile(speechFilePath), sentence }; } else { //开始计算得分 for (int i = 0; i < speechResult.Count; i++) { if (lan == "zh") { char[] words = SppechEvaluation.getSentenceWordsZh(speechResult[i]); tempScore = SppechEvaluation.calaAccuracySocre(enText, words); if (tempScore > accuracySocre) { accuracySocre = tempScore; } tempScore = SppechEvaluation.calaFluencySocreZh(enText, seconds); if (tempScore > fluencySocre) { fluencySocre = tempScore; } tempScore = SppechEvaluation.calaIntegritySocre(enText, words, accuracySocre); if (tempScore > integritySocre) { integritySocre = tempScore; } sentence = SppechEvaluation.getSentenceAccuracyZh(enText, speechResult); } else { string[] words = SppechEvaluation.getSentenceWords(speechResult[i]); //accuracySocre、fluencySocre、integritySocre取平均分,totalSocre取accuracySocre最高分 tempScore = SppechEvaluation.calaAccuracySocre(enText, words); if (tempScore > accuracySocre) { accuracySocre = tempScore; } tempScore = SppechEvaluation.calaFluencySocre(enText, seconds); if (tempScore > fluencySocre) { fluencySocre = tempScore; } tempScore = SppechEvaluation.calaIntegritySocre(enText, words, accuracySocre); if (tempScore > integritySocre) { integritySocre = tempScore; } sentence = SppechEvaluation.getSentenceAccuracy2(enText, speechResult); } } totalSocre = (int)((float)(accuracySocre * 60 + fluencySocre * 20 + integritySocre * 20) / 100); if (speechResult.Count == 0) { sentence = SppechEvaluation.getSentenceAccuracy3(enText, speechResult); } //return "{\"success\":true,\"message\":\"\",\"data\":{\"totalSocre\":\"" + totalSocre + "\",\"accuracySocre\":\"" + accuracySocre + "\",\"fluencySocre\":\"" + fluencySocre + "\",\"integritySocre\":\"" + integritySocre + "\",\"speechFilePath\":\"" + FileServices.urlConvertor(speechFilePath) + "\",\"speechSeconds\":\"" + seconds.ToString() + "\",\"sentence\":" + sentence + "}}"; apiResult.data = new { totalSocre, accuracySocre, fluencySocre, integritySocre, speechFilePath = UploadFile.PostFile(speechFilePath), speechSeconds = seconds.ToString(), sentence }; } apiResult.success = true; apiResult.message = "获取成功"; } catch (Exception ex) { return(new ApiResult() { success = false, message = ex.Message }); } finally { //删掉服务器上的文件 if (Util.isNotNull(speechFilePath)) { if (File.Exists(speechFilePath)) { File.Delete(speechFilePath); } } if (Util.isNotNull(silkFile)) { if (File.Exists(silkFile)) { File.Delete(silkFile); } } if (Util.isNotNull(otherFile)) { if (File.Exists(otherFile)) { File.Delete(otherFile); } } } return(apiResult); }
public ApiResult CutAudio() { ApiResult apiResult = new Models.ApiResult(); List <string> output_list = new List <string>(); string input = string.Empty; try { Dictionary <string, string> cut_files = new Dictionary <string, string>(); HttpFileCollection fileList = HttpContext.Current.Request.Files; if (fileList.Count < 1) { return(new ApiResult() { success = false, message = "文件为空" }); } HttpPostedFile file = fileList[0]; string folder = System.AppDomain.CurrentDomain.BaseDirectory + "NewSoundFiles/"; if (!System.IO.Directory.Exists(Path.GetDirectoryName(folder))) { System.IO.Directory.CreateDirectory(Path.GetDirectoryName(folder)); } //先保存文件 input = folder + "cutAudio_" + sys.getRandomStr() + Path.GetExtension(file.FileName); input = input.Replace("/", "\\"); file.SaveAs(input); string timespans = HttpContext.Current.Request.Form["timespans"]; string[] times = timespans.Split(new char[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries); string start = ""; string end = ""; List <string> cut_times = new List <string>(); foreach (string time in times) { if (Util.isNotNull(time)) { cut_times.Add(time); } } //没有结束时间,所以需要加上 string _all_audio_time = FfmpegHelper.getMediaDuration(input); string[] all_audio_times = _all_audio_time.Split(':'); string audio_times = (int.Parse(all_audio_times[0]) * 3600 + int.Parse(all_audio_times[1]) * 60 + double.Parse(all_audio_times[2])).ToString(); cut_times.Add(audio_times); //确保没有空数据 if (cut_times.Count > 1) { for (int i = 1; i < cut_times.Count; i++) { try { start = cut_times[i - 1]; TimeSpan _start = TimeSpan.FromSeconds(double.Parse(start)); end = cut_times[i]; TimeSpan _end = TimeSpan.FromSeconds(double.Parse(end) - double.Parse(start)); string output = folder + i + "_cutAudio_" + sys.getRandomStr() + Path.GetExtension(file.FileName); output = output.Replace("/", "\\"); output_list.Add(output); bool is_success = FfmpegHelper.CutAudioFile(input, output, _start, _end); //上传到服务器 if (File.Exists(output)) { string server_path = UploadFile.PostFile(output); cut_files.Add(start, server_path); } } catch (Exception ex) { return(new ApiResult() { success = false, message = "timespans参数不对" }); } } apiResult.success = true; apiResult.message = "截取成功"; apiResult.data = cut_files; } else { return(new ApiResult() { success = false, message = "timespans参数不对" }); } } catch (Exception ex) { return(new ApiResult() { success = false, message = ex.Message }); } finally { if (Util.isNotNull(input)) { if (File.Exists(input)) { File.Delete(input); } } foreach (string file in output_list) { if (Util.isNotNull(file)) { if (File.Exists(file)) { File.Delete(file); } } } } return(apiResult); }
/// <summary> /// 截取音频后,对每个小音频获语音转文字,一个音频对应一段文字 /// </summary> /// <param name="startMilliSecond"></param> /// <param name="endMilliSecond"></param> /// <param name="reader"></param> /// <param name="sound_path"></param> /// <param name="_name"></param> /// <param name="language"></param> /// <param name="splitTime"></param> private void GetBaiduSpeech(TimeSpan startMilliSecond, TimeSpan endMilliSecond, string sound_path, int i, string language, double splitTime, TimeSpan totalTime , int channel, int rate, int bit) { string newFile = ""; string _newFile = ""; bool need_delete = true; //将文件保存到新的文件夹(sound_path是原音频路径,newFolder是新的小音频路径,使用完成后将上传到服务器成功的音频删除) string newFolder = System.AppDomain.CurrentDomain.BaseDirectory + "NewSoundFiles/" + Path.GetFileNameWithoutExtension(sound_path) + "/"; try { #region 为截取音频做准备 //开始时间往前取startMilliSecond一半的偏移,结束时间往后取间隔时间的一半的偏移 if (i == 0) { startMilliSecond = startMilliSecond - TimeSpan.FromMilliseconds(startMilliSecond.TotalMilliseconds / 2); } else { startMilliSecond = startMilliSecond - TimeSpan.FromMilliseconds(splitTime / 2); } if (endMilliSecond < totalTime)//最后一次不用取偏移 { endMilliSecond = endMilliSecond + TimeSpan.FromMilliseconds(splitTime / 2); } TimeSpan span = endMilliSecond - startMilliSecond; #endregion string fileName = Path.GetFileNameWithoutExtension(sound_path) + "_" + i + Path.GetExtension(sound_path);//重命名文件 //重新存储到一个新的文件目录 if (!System.IO.Directory.Exists(newFolder)) { System.IO.Directory.CreateDirectory(newFolder); } //拼接后的文件路径 newFile = newFolder + fileName; if (!FfmpegHelper.CutAudioFile(sound_path, newFile, startMilliSecond, span)) { LogHelper.Error("第" + i + "次音频截取失败"); return; } //上传到文件服务器 string server_path = UploadFile.PostFile(newFile); if (Util.isNotNull(server_path)) { //上传成功 voiceFiles.Add(server_path); } else { need_delete = false; //上传失败,在服务器上的路径 voiceFiles.Add(Util.getServerPath() + "/NewSoundFiles/" + Path.GetFileNameWithoutExtension(sound_path) + "/" + fileName); } //大于60s的需要再处理 if (span.TotalSeconds >= 60)//音频大于60s,只截取50s { span = TimeSpan.FromSeconds(50); //保存新的音频文件 string _fileName = "_" + Path.GetFileNameWithoutExtension(sound_path) + "_" + i + ".wav";//重命名文件 _newFile = newFolder + _fileName; //截取音频 if (!FfmpegHelper.CutAudioFile(sound_path, _newFile, startMilliSecond, span)) { LogHelper.Error("第" + i + "次音频截取失败"); return; } //转成pcm //将音频转换为文字 baidu_text.Add(Rays.Utility.BadiAI.BaiduAI.BaiduTranslateToText(_newFile, language, rate.ToString())); } else { //将音频转换为文字 baidu_text.Add(Rays.Utility.BadiAI.BaiduAI.BaiduTranslateToText(newFile, language, rate.ToString())); } } catch (Exception ex) { LogHelper.Error("GetBaiduSpeech:" + ex.Message); } finally { //删除文件 if (File.Exists(_newFile)) { File.Delete(_newFile); } if (need_delete) { if (File.Exists(newFile)) { File.Delete(newFile); } } //删除目录 if (Directory.Exists(newFolder) && Directory.GetFiles(newFolder).Length == 0) { Directory.Delete(newFolder); } } }