从Windows 7服务播放wav / mp3

时间:2012-09-18 15:18:02

标签: c#-4.0 windows-7 windows-services naudio

我需要从Windows 7/2008中的服务播放声音文件(wav或mp3很好)...我们在WinXP中的操作方式不再适用。我已经按照这个问题Play wave file from a Windows Service (C#)以各种组合方式取得了成功。通过调试器播放声音很好但是一旦我将它作为服务安装它就不会播放,并且事件日志证明正在进行呼叫。我也跟着http://bresleveloper.blogspot.co.il/2012/06/c-service-play-sound-with-naudio.html链接得到了相同的结果。

以下是代码段。它是VS 2010,.Net 4.0,NAudio 1.5.4.0的C#服务。我在用 InstallUtil用于安装/删除服务。

WRT代码,我每次评论Wav或MP3的东西和其中一种方法......他们都成功地播放声音。

    static class Program
    {
        [DllImport("kernel32.dll")]
        public static extern Boolean AllocConsole();

        static void Main(string[] args)
        {
            m_eventLog = new EventLog();
            m_eventLog.Source = "EventLoggerSource";

            if(args.Length > 0 && args[0].ToLower() == "/console")
            {
                AllocConsole();
                EventLoggerApp app = new EventLoggerApp();
                app.Start();

                m_eventLog.WriteEntry("INFO (Calling Player)");
                string fileFullPath=@"c:\aaasound\bunny_troubles.wav",fileFullPath2=@"c:\aaasound\dreams.mp3";

                // Wav file
                IWavePlayer wavePlayer=new WaveOutEvent();  // Method 1
                IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Shared,false,100); // Method 2   
                AudioFileReader audioFile=new AudioFileReader(fileFullPath);
                audioFile.Volume = (float)1.0;
                wavePlayer.Init(audioFile);

                // MP3 file
                IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Shared,true,100); // Method 1- EventSync/not both work
                IWavePlayer wavePlayer=new WasapiOut(NAudio.CoreAudioApi.AudioClientShareMode.Exclusive,false,100); // Method 2- EventSync must be false or throws an exception
                WaveStream mp3Reader = new Mp3FileReader(fileFullPath2);
                WaveChannel32 inputStream=new WaveChannel32(mp3Reader);
                WaveStream wavStream=new WaveChannel32(inputStream);
                wavePlayer.Init(wavStream);

                //this.wavePlayer.PlaybackStopped += new EventHandler(wavePlayer_PlaybackStopped);
                wavePlayer.Play();
                while(wavePlayer.PlaybackState == PlaybackState.Playing)
                {
                    Thread.Sleep(100);
                }

0 个答案:

没有答案