是否可以使用SoundPlayer连续播放2种声音?

时间:2014-12-11 13:55:02

标签: c# visual-studio soundplayer

我正在寻找一种方法来异步播放多个声音。

我实际上有:

jouerSon("_" + nbre1);
jouerSon(operateur);
jouerSon("_" + nbre2);
jouerSon("equal");

public void jouerSon(String son)
{
    System.Media.SoundPlayer player = new SoundPlayer();
    player.Stream = Properties.Resources.ResourceManager.GetStream(son);
    // player.LoadAsync();
    player.Play();
    //Thread.Sleep(500);
    //player.Stop();
 }

我想播放第一个声音,然后在第二个声音播放时等等,而程序仍然响应。

我设法一个接一个地播放每个声音但只使用同步播放,这阻止了用户在播放所有声音之前做任何事情。

如果我尝试使用异步播放,则只播放最后一个声音而不是每个声音。

我四处寻找解决方案,但似乎找不到任何解决方案。有人能帮助我吗?

2 个答案:

答案 0 :(得分:0)

在不同的主题上播放:

    private void button1_Click(object sender, EventArgs e)
    {
        // ...
        jouerSon(new String[] { "_" + nbre1, operateur, "_" + nbre2, "equal" });
        // ...
    }

    public void jouerSon(String[] sons)
    {
        Task t = new Task(() =>
        {
            System.Media.SoundPlayer player = new System.Media.SoundPlayer();
            foreach (String son in sons)
            {
                player.Stream = Properties.Resources.ResourceManager.GetStream(son);
                player.PlaySync();
            }    
        });
        t.Start();
    }

或者可能是更专门定制的东西,例如:

    private void button1_Click(object sender, EventArgs e)
    {
        // ...
        jouerSon(nbre1, operateur, nbre2);
        // ...
    }

    public void jouerSon(string nbre1, string operateur, string nbre2)
    {
        Task t = new Task(() =>
        {
            System.Media.SoundPlayer player = new System.Media.SoundPlayer();
            player.Stream = Properties.Resources.ResourceManager.GetStream("_" + nbre1);
            player.PlaySync();
            player.Stream = Properties.Resources.ResourceManager.GetStream(operateur);
            player.PlaySync();
            player.Stream = Properties.Resources.ResourceManager.GetStream("_" + nbre2);
            player.PlaySync();
            player.Stream = Properties.Resources.ResourceManager.GetStream("equal");
            player.PlaySync();
        });
        t.Start();
    }

答案 1 :(得分:0)

好的,正如所承诺的,这里有一些如何使用Windows Media Player的示例代码。但是现在我看着它,我可以看到它比我想象的要复杂得多 - 可能太复杂了?

此程序可用于播放声音文件1次,2次,或n次,或不确定次数,直到调用程序调用StopPlayer()方法。修改它以播放第一个声音文件然后再播放另一个声音文件应该相当容易。

using WMPLib;

using System;


namespace Merlinia.CommonClasses
{
   /// <summary>
   /// This class provides a very simple wrapper layer for the Microsoft Windows Media Player.
   /// 
   /// Remember to call Dispose() when the player is no longer needed. (Actually, this may not be 
   /// necessary.)
   /// </summary>
   public class MMediaPlayer : IDisposable
   {
      #region Private variables

      // Reference to an Interop object for the COM object that interfaces with Microsoft Windows 
      //  Media Player
      private readonly WindowsMediaPlayer _windowsMediaPlayer = null;

      // Number of repeats left, negative = keep looping
      private int _repeatCount = -1;

      // Part of the IDisposable pattern
      private bool _isDisposed = false;

      #endregion Private variables


      #region Constructor

      /// <summary>
      /// Constructor.
      /// </summary>
      public MMediaPlayer()
      {
         try
         {
            // Instantiate the Windows Media Player Interop object 
            _windowsMediaPlayer = new WindowsMediaPlayer();

            // Hook up a couple of event handlers
            _windowsMediaPlayer.MediaError += WindowsMediaPlayer_MediaError;
            _windowsMediaPlayer.PlayStateChange += WindowsMediaPlayer_PlayStateChange;
         }
         catch (Exception e)
         {
            _cLog.Error(0x3ad3a52u, e);
         }
      }

      #endregion Constructor


      #region Public methods

      /// <summary>
      /// Method to start the media player playing a file.
      /// </summary>
      /// <param name="fileName">complete file name</param>
      /// <param name="repeatCount">zero = repeat indefinitely, else number of times to repeat</param>
      public void PlayMediaFile(string fileName, int repeatCount)
      {
         if (_windowsMediaPlayer == null)
            return;

         _repeatCount = --repeatCount;  // Zero -> -1, 1 -> zero, etc.

         if (_windowsMediaPlayer.playState == WMPPlayState.wmppsPlaying)
            _windowsMediaPlayer.controls.stop();  // Probably unnecessary

         _windowsMediaPlayer.URL = fileName;
         _windowsMediaPlayer.controls.play();
      }


      /// <summary>
      /// Method to stop the media player.
      /// </summary>
      public void StopPlayer()
      {
         if (_windowsMediaPlayer == null)
            return;

         _repeatCount = 0;
         _windowsMediaPlayer.controls.stop();
      }

      #endregion Public methods


      #region Private methods

      /// <summary>
      /// Event-handler method called by Windows Media Player when the media file can't be opened, 
      /// or some other error. This is logged, but otherwise ignored - the calling module is not 
      /// signaled in any way.
      /// </summary>
      private static void WindowsMediaPlayer_MediaError(object pMediaObject)
      {
         _cLog.Error(0x3ad1d3bu);
      }


      /// <summary>
      /// Event-handler method called by Windows Media Player when the "state" of the media player 
      /// changes. This is used to repeat the playing of the media for the specified number of 
      /// times, or maybe for an indeterminate number of times.
      /// </summary>
      private void WindowsMediaPlayer_PlayStateChange(int newState)
      {
         if ((WMPPlayState)newState == WMPPlayState.wmppsStopped)
         {
            if (_repeatCount != 0)
            {
               _repeatCount--;
               _windowsMediaPlayer.controls.play();
            }
         }
      }

      #endregion Private methods


      #region IDisposable stuff

      // This copied from here: http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

      /// <summary>
      /// Method to implement IDisposable. Do not make this method virtual - a derived class should 
      /// not be able to override this method.
      /// </summary>
      public void Dispose()
      {
         // Call the following method
         Dispose(true);

         // This object will be cleaned up by the Dispose() method below. Therefore, we call 
         //  GC.SuppressFinalize to take this object off the finalization queue and prevent 
         //  finalization code for this object from executing a second time.
         GC.SuppressFinalize(this);
      }


      /// <summary>
      /// Dispose(bool disposing) executes in two distinct scenarios. If isDisposing equals true, 
      /// the method has been called directly or indirectly by a user's code. Managed and unmanaged 
      /// resources can be disposed. If isDisposing equals false, the method has been called by the 
      /// runtime from inside the finalizer and you should not reference other objects - only 
      /// unmanaged resources can be disposed.
      /// </summary>
      protected virtual void Dispose(bool isDisposing)
      {
         // Check to see if Dispose() has already been called
         if (!_isDisposed)
         {
            // If isDisposing equals true, dispose all managed and unmanaged resources
            if (isDisposing && _windowsMediaPlayer != null)
            {
               // Close the media player. (This may not be necessary?)
               _windowsMediaPlayer.close();
            }

            // Note disposing has been done
            _isDisposed = true;
         }
      }

      #endregion IDisposable stuff

   }
}

忽略与日志记录有关的陈述。

但是要使其工作,您需要一个与Windows Media Player接口的COM对象的Interop dll。不幸的是,如果你以前从未这样做过,那就有点棘手了。 Visual Studio能够生成Interop dll。或者,您可以尝试在Internet上找到一个。这就是我事实上所做的,我碰巧在这里找到了一个: http://grouplab.cpsc.ucalgary.ca/cookbook/index.php/VisualStudio/HowToUseWindowsMediaPlayerToPlayAudioAndVideo

祝你好运,欢迎你来询问你是否尝试这样做并遇到问题。