[C#] mciSendString多线程操作录音失败,返回263错误码

本文介绍了一种解决mciSendString在多线程应用中录音失败的方法。通过创建一个安全调用类mciSafeCall,并利用Windows消息机制确保mciSendString在主线程中执行,从而避免了因多线程导致的INVALID_DEVICE_NAME错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值