C# 讯飞语音唤醒

public partial class MainWindow : Window
{

    // 导入 C/C++ 的库文件
    [DllImport("msc_x64.dll", CallingConvention = CallingConvention.Winapi)]
    public static extern int MSPLogin(string username, string password, string loginParams);

    [DllImport("msc_x64.dll", CallingConvention = CallingConvention.Winapi)]
    public static extern int MSPLogout();

    [DllImport("msc_x64.dll", CallingConvention = CallingConvention.Winapi)]
    public static extern IntPtr QIVWSessionBegin(string grammarList, string sessionParams, out int errorCode);

    [DllImport("msc_x64.dll", CallingConvention = CallingConvention.Winapi)]
    public static extern int QIVWRegisterNotify(IntPtr sessionID, IVWMessageCallback callback, IntPtr userData);

    [DllImport("msc_x64.dll", CallingConvention = CallingConvention.Winapi)]
    public static extern int QIVWAudioWrite(IntPtr sessionID, IntPtr audioData, uint audioLen, int audioStatus);

    [DllImport("msc_x64.dll", CallingConvention = CallingConvention.Winapi)]
    public static extern int QIVWSessionEnd(IntPtr sessionID, string hints);

    // 定义回调函数类型
    public delegate int IVWMessageCallback(string sessionID, int msg, int param1, int param2, IntPtr info, IntPtr userData);




    const int MSP_SUCCESS = 0;
    const int MSP_AUDIO_SAMPLE_CONTINUE = 1;
    const int MSP_AUDIO_SAMPLE_FIRST = 2;
    const int MSP_AUDIO_SAMPLE_LAST = 4;
    const int CALLBACK_EVENT = 32768;

    // 定义 WAVEFORMATEX 结构体
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 2)]
    public struct WAVEFORMATEX
    {
        public ushort wFormatTag;
        public ushort nChannels;
        public uint nSamplesPerSec;
        public uint nAvgBytesPerSec;
        public ushort nBlockAlign;
        public ushort wBitsPerSample;
        public ushort cbSize;
    }

    // 定义 WAVEHDR 结构体
    [StructLayout(LayoutKind.Sequential)]
    public struct WAVEHDR
    {
        public IntPtr lpData;
        public uint dwBufferLength;
        public uint dwBytesRecorded;
        public IntPtr dwUser;
        public uint dwFlags;
        public uint dwLoops;
        public IntPtr lpNext;
        public uint reserved;
    }

    [DllImport("winmm.dll")]
    public static extern int waveInOpen(out IntPtr hWaveIn, int uDeviceID, ref WAVEFORMATEX lpFormat, IntPtr dwCallback, int dwInstance, int dwFlags);

    [DllImport("winmm.dll")]
    public static extern int waveInStart(IntPtr hWaveIn);

    [DllImport("winmm.dll")]
    public static extern int waveInPrepareHeader(IntPtr hWaveIn, ref WAVEHDR lpWaveInHdr, int uSize);

    [DllImport("winmm.dll")]
    public static extern int waveInAddBuffer(IntPtr hWaveIn, ref WAVEHDR lpWaveInHdr, int uSize);

    [DllImport("winmm.dll")]
    public static extern int waveInReset(IntPtr hWaveIn);

    [DllImport("winmm.dll")]
    public static extern int waveInClose(IntPtr hWaveIn);

    const int FRAME_LEN = 640;
    const int bufsize = 1024 * 500;
    IntPtr hWaveIn;  //输入设备
    public  void ivw_demo_microphone(string grammar_list, string session_begin_params)
    {
        retask:
        IntPtr session_id = IntPtr.Zero;
        int err_code = MSP_SUCCESS;
        long audio_size = 0;
        long audio_count = 0;
        int count = 0;
        int audio_stat = MSP_AUDIO_SAMPLE_CONTINUE;
        string sse_hints = "";
        long len = 0;

        IntPtr hWaveIn = IntPtr.Zero;
        WAVEFORMATEX waveform = new WAVEFORMATEX();
        IntPtr pBuffer = IntPtr.Zero;
        WAVEHDR wHdr = new WAVEHDR();
        AutoResetEvent wait = new AutoResetEvent(false);

        waveform.wFormatTag = 1;
        waveform.nSamplesPerSec = 16000;
        waveform.wBitsPerSample = 16;
        waveform.nChannels = 1;
        waveform.nAvgBytesPerSec = 16000;
        waveform.nBlockAlign = 2;
        waveform.cbSize = 0;

        wait = new AutoResetEvent(false);

        waveInOpen(out hWaveIn, -1, ref waveform, wait.SafeWaitHandle.DangerousGetHandle(), 0, CALLBACK_EVENT);


        session_id = QIVWSessionBegin(grammar_list, session_begin_params, out err_code);
        if (err_code != MSP_SUCCESS)
        {
            Console.WriteLine("QIVWSessionBegin failed! error code: " + err_code);
            goto exit;
        }
        try
        {
            err_code = QIVWRegisterNotify(session_id, cb_ivw_msg_proc, IntPtr.Zero);
        }
        catch (Exception)
        {

        }
       
        if (err_code != MSP_SUCCESS)
        {
            sse_hints = "QIVWRegisterNotify errorCode=" + err_code;
            Console.WriteLine("QIVWRegisterNotify failed! error code: " + err_code);
            goto exit;
        }

        pBuffer = Marshal.AllocHGlobal(bufsize);
        wHdr.lpData = pBuffer;
        wHdr.dwBufferLength = bufsize;
        wHdr.dwBytesRecorded = 0;
        wHdr.dwUser = IntPtr.Zero;
        wHdr.dwFlags = 0;
        wHdr.dwLoops = 1;

        waveInPrepareHeader(hWaveIn, ref wHdr, Marshal.SizeOf(wHdr));
        waveInAddBuffer(hWaveIn, ref wHdr, Marshal.SizeOf(wHdr));
        waveInStart(hWaveIn);



        while (audio_count < bufsize)
        {
            if (awaken_flag)
            {
                break;
            }
            Thread.Sleep(200);

            len = 10 * FRAME_LEN;
            audio_stat = MSP_AUDIO_SAMPLE_CONTINUE;

            if (audio_count >= wHdr.dwBytesRecorded)
            {
                len = audio_size;
                audio_stat = MSP_AUDIO_SAMPLE_LAST;
            }

            if (audio_count == 0)
            {
                audio_stat = MSP_AUDIO_SAMPLE_FIRST;
            }

            //Console.WriteLine("csid=" + session_id + ",count=" + count++ + ",aus=" + audio_stat + "audio_count---------" + audio_count);

            err_code = QIVWAudioWrite(session_id, IntPtr.Add(pBuffer, (int)audio_count), (uint)len, audio_stat);

            if (MSP_SUCCESS != err_code)
            {
                Console.WriteLine("QIVWAudioWrite failed! error code: " + err_code);
                sse_hints = "QIVWAudioWrite errorCode=" + err_code;
                goto exit;
            }
            if (MSP_AUDIO_SAMPLE_LAST == audio_stat)
            {
                break;
            }

            audio_count += len;
        }



        waveInReset(hWaveIn);

        if (pBuffer != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(pBuffer);
        }

        sse_hints = "success";

    exit:
        if (session_id != IntPtr.Zero)
        {
            QIVWSessionEnd(session_id, sse_hints);
        }

        if (!awaken_flag)
        {
            goto retask;
        }
        
        while (awaken_flag)
        {
            Thread.Sleep(100);
           // Console.WriteLine("灯带"+ awaken_flag);
            if (!awaken_flag)
            {
                  
                goto retask;
            }
        }
    }


     bool  awaken_flag=false;
    private  int cb_ivw_msg_proc(string sessionID, int msg, int param1, int param2, IntPtr info, IntPtr userData)
    {
        try
        {
            IvwMessage ivwMsg = (IvwMessage)msg;
            if (ivwMsg == IvwMessage.MSP_IVW_MSG_ERROR) //唤醒出错消息
            {
                Console.WriteLine("\nMSP_IVW_MSG_ERROR error code: " + param1);
                awaken_flag = false;
            }
            else if (ivwMsg == IvwMessage.MSP_IVW_MSG_WAKEUP) //唤醒成功消息
            {
                string result = Marshal.PtrToStringAnsi(info);
                Console.WriteLine("\nMSP_IVW_MSG_WAKEUP result: " + result);

               
                try
                {
                    JObject jsonObject = JObject.Parse(result);
                    int score = (int)jsonObject["score"];
                    Console.WriteLine("score: " + score);
                }catch(Exception e) { }

                awaken_flag = true;
                Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    myImage_t.Visibility = Visibility.Visible;
                    myImage_d.Visibility = Visibility.Hidden;
                    myImage_x.Visibility = Visibility.Hidden;

                    uc_ai ai = new uc_ai();
                    ai.tbmsg.Text = "您好,请问有什么可以帮助您?";
                    spliao.Children.Add(ai);
                });
                // 启动计时器,监听暂停 10 秒
                listenTimer.Start();

            }
        }
        catch (Exception)
        {

        }
     
        return 0;
    }


    public enum IvwMessage
    {
        MSP_IVW_MSG_WAKEUP = 1,
        MSP_IVW_MSG_ERROR = 2,
        MSP_IVW_MSG_ISR_RESULT = 3,
        MSP_IVW_MSG_ISR_EPS = 4,
        MSP_IVW_MSG_VOLUME = 5,
        MSP_IVW_MSG_ENROLL = 6,
        MSP_IVW_MSG_RESET = 7
    }









    private System.Timers.Timer listenTimer;
    int ret = MSP_SUCCESS;
    const string lgi_param = "appid = 80932b17, work_dir = .";
    const string ssb_param = "ivw_threshold=0:2000,sst=wakeup,ivw_res_path =fo|res/ivw/wakeupresource.jet";
    public MainWindow()
    {
        InitializeComponent();
       
        /* 用户登录 */
        ret = MSPLogin(null, null, lgi_param);

        // 初始化计时器
        listenTimer = new System.Timers.Timer();
        listenTimer.Interval = 5000; // 5秒
        listenTimer.Elapsed += ListenTimer_Elapsed; // 设置计时器触发时的处理方法
     


        Task.Run(()=>{
            ivw_demo_microphone(null, ssb_param);
        });

    }


    private void ListenTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (awaken_flag)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                myImage_t.Visibility = Visibility.Hidden;
                myImage_d.Visibility = Visibility.Visible;
                myImage_x.Visibility = Visibility.Hidden;
            });
            listenTimer.Stop();

            awaken_flag = false;
        }
    }






































    private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        DragMove();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {

        // 获取在XAML中定义的Storyboard
        Storyboard myStoryboard = FindResource("Storyboardmin") as Storyboard;

        if (myStoryboard != null)
        {
            // 启动Storyboard动画
            myStoryboard.Begin();
        }
    }

    private void window_Loaded(object sender, RoutedEventArgs e)
    {
        double screenWidth = SystemParameters.WorkArea.Width;
        double screenHeight = SystemParameters.WorkArea.Height;

        // 设置窗口的初始位置
        Left = screenWidth - Width;
        Top = screenHeight - Height;
    }
   

    private void ReverseAnimation()
    {
        Storyboard reverseStoryboard = new Storyboard();

        // 创建宽度反向动画
        DoubleAnimation reverseWidthAnimation = new DoubleAnimation();
        reverseWidthAnimation.To = 1; // 回到原始宽度
        reverseWidthAnimation.Duration = new Duration(TimeSpan.FromSeconds(1)); // 反向动画持续时间
        Storyboard.SetTarget(reverseWidthAnimation, grid);
        Storyboard.SetTargetProperty(reverseWidthAnimation, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"));
        reverseStoryboard.Children.Add(reverseWidthAnimation);

        // 创建高度反向动画
        DoubleAnimation reverseHeightAnimation = new DoubleAnimation();
        reverseHeightAnimation.To = 1; // 回到原始高度
        reverseHeightAnimation.Duration = new Duration(TimeSpan.FromSeconds(1)); // 反向动画持续时间
        Storyboard.SetTarget(reverseHeightAnimation, grid);
        Storyboard.SetTargetProperty(reverseHeightAnimation, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"));
        reverseStoryboard.Children.Add(reverseHeightAnimation);

        // 创建位移反向动画
        DoubleAnimation reverseTranslateXAnimation = new DoubleAnimation();
        reverseTranslateXAnimation.To = 0; // 水平方向不移动
        reverseTranslateXAnimation.Duration = new Duration(TimeSpan.FromSeconds(1)); // 反向动画持续时间
        Storyboard.SetTarget(reverseTranslateXAnimation, grid);
        Storyboard.SetTargetProperty(reverseTranslateXAnimation, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"));
        reverseStoryboard.Children.Add(reverseTranslateXAnimation);

        DoubleAnimation reverseTranslateYAnimation = new DoubleAnimation();
        reverseTranslateYAnimation.To = 0; // 垂直方向不移动
        reverseTranslateYAnimation.Duration = new Duration(TimeSpan.FromSeconds(1)); // 反向动画持续时间
        Storyboard.SetTarget(reverseTranslateYAnimation, grid);
        Storyboard.SetTargetProperty(reverseTranslateYAnimation, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"));
        reverseStoryboard.Children.Add(reverseTranslateYAnimation);

        // 创建可见性反向动画
        ObjectAnimationUsingKeyFrames reverseVisibilityAnimation = new ObjectAnimationUsingKeyFrames();
        reverseVisibilityAnimation.KeyFrames.Add(new DiscreteObjectKeyFrame(Visibility.Visible, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0))));
        reverseVisibilityAnimation.KeyFrames.Add(new DiscreteObjectKeyFrame(Visibility.Visible, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1))));
        Storyboard.SetTarget(reverseVisibilityAnimation, grid);
        Storyboard.SetTargetProperty(reverseVisibilityAnimation, new PropertyPath("(UIElement.Visibility)"));
        reverseStoryboard.Children.Add(reverseVisibilityAnimation);

        // 开始反向动画
        reverseStoryboard.Begin();
    

     
    }

    private void Image_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        Point windowTopLeft = this.PointToScreen(new Point(0, 0));
        double leftMargin = windowTopLeft.X;
        double targetLeft = SystemParameters.WorkArea.Right - Width;
        if (leftMargin != targetLeft)
        {

            DoubleAnimation animation = new DoubleAnimation();
            animation.From = this.Left; // 当前左侧位置
            animation.To = targetLeft; // 目标左侧位置
            animation.Duration = TimeSpan.FromSeconds(1);

            this.BeginAnimation(Window.LeftProperty, animation);

            //this.Left = targetLeft;
        }

        ReverseAnimation();
    }

    private void Image_PreviewMouseUp_1(object sender, MouseButtonEventArgs e)
    {
        // 获取在XAML中定义的Storyboard
        Storyboard myStoryboard = FindResource("Storyboardmin") as Storyboard;

        if (myStoryboard != null)
        {
            myStoryboard.Completed += (senderss, es) =>
            {
                myImage_t.Visibility = Visibility.Hidden;
                myImage_d.Visibility = Visibility.Hidden;
                myImage_x.Visibility = Visibility.Visible;
            };
            // 启动Storyboard动画
            myStoryboard.Begin();
        }
    }

    private async void Button_Click_1(object sender, RoutedEventArgs e)
    {
        uc_me me = new uc_me();
        me.tbmsg.Text = "人工智能的用处";
        me.Margin = new Thickness(300, 0, 0, 0);
        spliao.Children.Add(me);
        await Task.Delay(1000);
        uc_ai ai = new uc_ai();
        ai.tbmsg.Text = "人工智能(AI)在各个领域都有广泛的用途,以下是一些主要用途的示例:\r\n\r\n1. **自然语言处理 (NLP):** AI被用于文本和语音处理,例如语音识别、文本翻译、情感分析、智能助手(如聊天机器人)等。\r\n\r\n2. **计算机视觉:** AI可以识别图像和视频内容,用于人脸识别、物体检测、图像分类、视频分析等领域。\r\n\r\n3. **自动驾驶:** 自动驾驶汽车使用AI来感知周围环境,做出决策并控制车辆,以实现无人驾驶。\r\n\r\n4. **医疗保健:** AI用于医学图像分析、疾病诊断、药物发现、个性化治疗、健康管理等。\r\n\r\n5. **金融服务:** AI被用于欺诈检测、信用评分、投资策略、股票交易、客户支持等金融领域的应用。\r\n\r\n6. **制造业:** AI用于自动化生产线、质量控制、供应链优化、预测性维护等。\r\n\r\n7. **教育:** 个性化教育、智能辅导系统、学习分析等。\r\n\r\n8. **游戏开发:** AI被用于游戏中的角色行为、虚拟世界模拟、智能敌人等。\r\n\r\n9. **机器人技术:** AI机器人用于服务业、医疗、军事、清洁、教育等领域。\r\n\r\n10. **科学研究:** AI在各个科学领域中都有用武之地,用于数据分析、模拟、探索未知等。\r\n\r\n11. **环境保护:** AI可以用于监测大气污染、水质、气候模型等,以支持环保努力。\r\n\r\n12. **政府服务:** AI可用于改进公共服务,如智能交通管理、城市规划、公共卫生等。\r\n\r\n13. **娱乐:** AI在游戏、虚拟现实、增强现实、音乐和艺术创作等方面有应用。\r\n\r\n14. **军事和安全:** AI用于军事情报分析、自动目标识别、网络安全等。\r\n\r\n15. **商业智能:** AI在数据分析、预测、市场营销、客户关系管理等方面有广泛应用。\r\n\r\n总的来说,人工智能可以提高效率、减少成本、增加创新、改善决策制定,对社会各个方面都有积极的影响。然而,同时也需要关注伦理和隐私问题,并确保AI系统的公平性和透明度。";
        spliao.Children.Add(ai);
    }

    private void Button_MouseEnter(object sender, MouseEventArgs e)
    {
        myImage_t.Visibility = Visibility.Visible;
        myImage_d.Visibility = Visibility.Hidden;
        myImage_x.Visibility = Visibility.Hidden;
    }

    private void Button_MouseLeave(object sender, MouseEventArgs e)
    {
        myImage_t.Visibility = Visibility.Hidden;
        myImage_d.Visibility = Visibility.Visible;
        myImage_x.Visibility = Visibility.Hidden;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值