用C#写一个报时软件

前段时间下载了一个安卓应用“明星整点报时”,觉得挺好用。就想自己动手写一个Windows上的报时软件;

报时分两种:

明星报时,也就是播放固定的语音文件;

语音报时,通过文字转语音达到目的;

播放语音文件
C#类System.Media. SoundPlayer可实现.wav文件的播放控制。


        /// <summary>

        /// 播放音频文件

        /// </summary>

        /// <param name="fileInfo">wav文件路径</param>

        private void PlayAudio(string fileInfo)

        {

            SoundPlayer player = new SoundPlayer(fileInfo);

            player.Play();

        }

但是无法播放wma,mp3等音频。

因为我下载到的明星报时语音包多以wma和mp3为主,所以我使用另外一种方式来播放。


        [System.Runtime.InteropServices.DllImport("winmm.dll")]

        public static extern uint mciSendString(string lpstrCommand, string lpstrReturnString, uint uReturnLength, uint hWndCallback);

 

        private void PlayAudioByAPI(string file)

        {

            mciSendString(@"close temp_alias", null, 0, 0);

            mciSendString("open \"" + file + "\" alias temp_alias", null, 0, 0);

            mciSendString("play temp_alias", null, 0, 0);

        }

这里使用了WindowsMediaPlayer的API,实现音频文件的播放。只要你的WMP能播的音频,就能在你程序中播放。

文字转语音
Windows有文字转语音功能,C#提供了调用的类库Interop.SpeechLib.dll。

使用方法很简单,在你的项目中添加Interop.SpeechLib.dll引用,在类中引用:

using SpeechLib;
添加方法:


        private void Speek(string message)

        {

            try

            {

                SpVoice Voice = new SpVoice();

                Voice.Voice = Voice.GetVoices().Item(0);

                Voice.Speak(message, SpeechVoiceSpeakFlags.SVSFlagsAsync);

            }

            catch (Exception ex)

            {

                //TODO

            }

        }

 

Voice.GetVoices().Item(0);  可以通过下标选择不同的语音引擎,这取决于你电脑上安装的语音引擎数量;

注:在Win7系统以前,windows系统默认没有安装语音包(可打开“控制面板”->“语音识别”->“文字到语音转换”查看),若没有语音包,则此功能无法实现;

下载: Interop.SpeechLib
原文地址:https://www.cnblogs.com/ruishuang208/p/3072692.html