【实例简介】
【实例截图】
【核心代码】
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using ponentModel;
using System.IO;
using ;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using BATT.AudioModule;
namespace BATT
{
public partial class Form1 : Form
{
private BackgroundWorker backgroundWorker = new BackgroundWorker();
private string resultStr;
private bool isRecord = false;
private string accessToken = null;
private SpeechModel speechModel = new SpeechModel();
private AutomaticSpeechRecognition testASR;
private string tempStr = ""; // 存储转换后的音频文件的临时目录
private ISpeechRecorder recorder = new NAudioRecorder();
private bool switchRecord = true;
private string str = null;
public Form1()
{
InitializeComponent();
testASR = new AutomaticSpeechRecognition(speechModel);
// 绑定拖放事件
richTextBoxResult.AllowDrop = true;
}
private void Form1_Load(object sender, EventArgs e)
{
// 向comboBox添加数据
List> listItems = new List>();
listItems.Add(new KeyValuePair("中文", "zh"));
listItems.Add(new KeyValuePair("英语", "en"));
listItems.Add(new KeyValuePair("粤语", "ct"));
comboBoxLan.DataSource = listItems;
comboBoxLan.DisplayMember = "Key";
comboBoxLan.ValueMember = "Value";
comboBoxLan.SelectedIndex = 0;
// 绑定事件以实现异步化
backgroundWorker.DoWork = new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerCompleted = new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
// 从文件中获取令牌,避免远程服务器上的请求过多
if (!File.Exists(@". oken.dat"))
{
accessToken = testASR.GetStrAccess(); // 令牌文件不存在,发送请求
}
else
{
string[] tokenInfo = File.ReadAllLines(@". oken.dat");
// 检查令牌是否过期
if (Convert.ToInt32(tokenInfo[1]) > ClassUtils.CurrentTime2Second())
{
accessToken = tokenInfo[0];
}
else
{
accessToken = testASR.GetStrAccess(); // 过期,再次请求刷新
}
}
speechModel.APIAccessToken = accessToken; // 更新 模式中的令牌
#region 鼠标悬停时显示提示
ToolTip toolTip = new ToolTip();
toolTip.SetToolTip(buttonRecord, "录音/停止录音");
toolTip.SetToolTip(comboBoxLan, "选择识别语言");
toolTip.SetToolTip(richTextBoxResult, "识别语音的内容");
#endregion
}
///
/// 开始录音/停止录音
///
///
///
private void buttonRecord_Click(object sender, EventArgs e)
{
if (switchRecord)
{
switchRecord = false; // 切换录音状态
buttonRecord.BackgroundImage = (Bitmap)Properties.Resources.ResourceManager.GetObject("采集结束");
if (recorder == null)
{
recorder = new NAudioRecorder();
}
recorder.SetFileName("record.wav");
recorder.StartRec();
labelInfo.ForeColor = Color.SpringGreen;
labelInfo.Text = "记录:正在采集.";
}
else
{
switchRecord = true;
buttonRecord.BackgroundImage = (Bitmap)Properties.Resources.ResourceManager.GetObject("正在采集");
if (recorder == null)
{
return;
}
isRecord = true;
recorder.StopRec();
recorder = null;
string filePath = Environment.CurrentDirectory @" ecord.wav";
StartRecognize(filePath);
}
}
private void button1_Click(object sender, EventArgs e)
{
richTextBoxResult.Clear();
}
private void StartRecognize(string apiRecord)
{
WavInfo wav = ClassUtils.GetWavInfo(apiRecord);
//数据量 = (采样频率 × 采样位数 × 声道数 × 时间) / 8
//if ((double)(wav.datasize * 8) / (wav.dwsamplespersec * wav.wbitspersample * wav.wchannels) > 60)
//{
// labelInfo.ForeColor = Color.HotPink;
// labelInfo.Text = "Error: The audio file is too large!";
//}
// 非8k/16k, 16bit 位深, 单声道的,进行格式转换
if (apiRecord.EndsWith(".mp3", StringComparison.CurrentCultureIgnoreCase)
|| int.Parse(wav.dwsamplespersec.ToString()) != 16000
|| int.Parse(wav.wbitspersample.ToString()) != 16
|| int.Parse(wav.wchannels.ToString()) != 1)
{
apiRecord = ClassUtils.Convert2Wav(apiRecord); // 音频文件转换为16k,16bit wav
tempStr = apiRecord;
}
labelInfo.ForeColor = Color.SpringGreen;
labelInfo.Text = "正在采集...";
KeyValuePair keyVal = (KeyValuePair)comboBoxLan.SelectedItem;
speechModel.APILanguage = keyVal.Value; // 在组合框中获取值
if (backgroundWorker.IsBusy != true)
{
this.backgroundWorker.RunWorkerAsync(); // 做耗时的任务
}
}
#region 异步工作
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// 表示这是录制的音频
if (isRecord)
{
speechModel.APIRecord = System.Environment.CurrentDirectory @" ecord.wav";
isRecord = false;
}
// 表示转换工作已经完成
if (tempStr != "")
{
speechModel.APIRecord = tempStr;
}
resultStr = testASR.GetStrText() " ";
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.richTextBoxResult.Text = resultStr;
labelInfo.ForeColor = Color.SpringGreen;
labelInfo.Text = "识别完成!";
// 完成识别,删除临时目录
if (tempStr != "")
{
Directory.Delete(Path.GetDirectoryName(tempStr), true); // 递归删除目录或子目录
}
}
#endregion
}
}
如果觉得《百度语音识别(采集麦克风声音 并自动转为文字)》对你有帮助,请点赞、收藏,并留下你的观点哦!