4

我需要在 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);
                }
4

0 回答 0