使用mciSendString进行录音,利用Timer定时器,一段时间后结束录音,保存录音文件,但是没有录音文件生成,查看mciSendString返回值,返回263(错误码对应的错误信息为INVALID_DEVICE_NAME)。查询资料后有人说mciSendString不支持多线程操作,在codeproject上找到解决方案,记录并分享给大家。
codeproject上页面https://www.codeproject.com/questions/183548/how-to-use-mcisendstring-in-a-threaded-application 中SebaSOR提供的处理方式
using System;
using System.Threading;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class mciSafeCall
{
[DllImport("winmm.dll")]
private static extern int mciSendString(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);
private int syncMciResult;
private string syncMciCommand;
private Form formulario;
public mciSafeCall(Form form)
{
formulario = form;
syncMciCommand = "";
}
public void mciReplacement(string Command)
{
syncMciCommand = Command;
if (!string.IsNullOrEmpty(syncMciCommand))
{
if (formulario.InvokeRequired)
formulario.Invoke(new Action(() =>
{
syncMciResult = mciSendString(syncMciCommand, null, 0, IntPtr.Zero);
}));
else
syncMciResult = mciSendString(syncMciCommand, null, 0, IntPtr.Zero);
}
}
}