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



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

我实际上有:

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();
 }

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

我设法一个接一个地播放每个声音,但只使用同步播放,这会阻止用户在播放所有声音之前执行任何操作。

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

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

在不同的线程上播放它们:

    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();
    }

好的,正如承诺的那样,这里有一些如何使用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对象的互操作dll。不幸的是,如果您以前从未这样做过,这有点棘手。Visual Studio能够生成Interop dll。或者,您可以尝试在互联网上找到一个。事实上,这就是我所做的,我碰巧在这里找到了一个:http://grouplab.cpsc.ucalgary.ca/cookbook/index.php/VisualStudio/HowToUseWindowsMediaPlayerToPlayAudioAndVideo

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

最新更新