[C#] mciSendString多線程操作錄音失敗,返回263錯誤碼

使用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);

        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章