提示语音播放

  
  SoundPlayApi.GetInstance().Speak("未识别到体温,请退出重试");
  SoundPlayApi.GetInstance().PlayVoice(@"voice\未测到体温.wav");


using System;
using System.Media;
using System.Speech.Synthesis;

namespace SoudPlayCom
{
    public class SoundPlayApi
    {

        public static SoundPlayApi GetInstance()
        {
            if (instance == null)
            {
                instance = new SoundPlayApi();
            }
            return instance;
        }
        private SoundPlayApi()
        {
            player = new SoundPlayer();
            _SpeechSynthesizer = new SpeechSynthesizer();
            try
            {
                _SpeechSynthesizer.SetOutputToDefaultAudioDevice();

            }
            catch (Exception ex)
            {

            }

            app_path = System.AppDomain.CurrentDomain.BaseDirectory;
        }

        private string app_path;
        private static SoundPlayApi instance;
        private SoundPlayer player;
        private SpeechSynthesizer _SpeechSynthesizer;
        public Prompt CurrentPrompt { get; set; }
        public bool PlayVoice(string file_path)
        {
            if (DateTime.Now.Hour == 12 || DateTime.Now.Hour == 13)
            {
                return true;
            }
            if (System.IO.File.Exists(file_path))
            {
                player.Stop();

                //存在文件

                player.SoundLocation = app_path + file_path;
                player.Play();//简单播放一遍
            }
            else
            {
                return false;
            }
            return true;
            //player.PlayLooping();//循环播放
            //player.PlaySync();//另起线程播放
        }
        public bool Speak(string txt)
        {
            if (DateTime.Now.Hour == 12 || DateTime.Now.Hour == 13)
            {
                return true;
            }
            if (string.IsNullOrEmpty(txt))
            {
                return false;
            }
            CancelCurrentPrompt();
            try
            {
                _SpeechSynthesizer.Volume = 100;
                CurrentPrompt = _SpeechSynthesizer.SpeakAsync(txt);
            }
            catch (Exception ex)
            {
                return false;
            }


            return true;
        }
        private void CancelCurrentPrompt()
        {
            if (CurrentPrompt != null)
            {
                try
                {
                    _SpeechSynthesizer.SpeakAsyncCancel(CurrentPrompt);
                }
                catch (Exception ex)
                {

                }

            }
            CurrentPrompt = null;
        }
    }


}

  

posted @ 2021-01-13 11:18  飞鱼上树了  阅读(69)  评论(0编辑  收藏  举报
/* 看板娘 */