播放声音,等待它完成然后做点什么?
时间:2020-03-06 14:52:26 来源:igfitidea点击:
我正在编写一个Windows Forms应用程序,该应用程序应该播放三个声音文件,并且在每个声音文件的末尾都将更改图像的来源。
我可以使用" System.Media.SoundPlayer"来播放声音。但是,似乎在继续播放声音。
这样做的最终效果是仅播放最后一个声音,并且更改所有图像。
我试过了" Thread.Sleep",但是它使整个GUI进入睡眠状态,并且在进入睡眠状态之后,所有的一切都会立即发生,并且会播放最后一个声音。
更新
我以为PlaySynch在工作,但似乎冻结了我的GUI,这不理想。我还可以做些什么?
解决方案
我们是否尝试过SoundPlayer.PlaySync方法?从帮助中:
The PlaySync method uses the current thread to play a .wav file, preventing the thread from handling other messages until the load is complete.
代替使用Play方法,而使用PlaySync方法。
我们可能想要做的是发出异步声音,然后以不响应用户响应的方式禁用UI。然后,在播放声音后,我们将重新启用UI。这将使我们仍然可以正常绘制UI。
我想出了怎么做。我使用了PlaySynch,但我在绘制线程UI的代码中使用了单独的线程进行播放。播放每个文件后,同一线程还将更新UI。
使用此代码:
[DllImport("WinMM.dll")] public static extern bool PlaySound(byte[]wfname, int fuSound); // flag values for SoundFlags argument on PlaySound public static int SND_SYNC = 0x0000; // Play synchronously (default). public static int SND_ASYNC = 0x0001; // Play asynchronously. public static int SND_NODEFAULT = 0x0002; // Silence (!default) if sound not found. public static int SND_MEMORY = 0x0004; // PszSound points to a memory file. public static int SND_LOOP = 0x0008; // Loop the sound until next sndPlaySound. public static int SND_NOSTOP = 0x0010; // Don't stop any currently playing sound. public static int SND_NOWAIT = 0x00002000; // Don't wait if the driver is busy. public static int SND_ALIAS = 0x00010000; // Name is a registry alias. public static int SND_ALIAS_ID = 0x00110000; // Alias is a predefined ID. public static int SND_FILENAME = 0x00020000; // Name is file name. public static int SND_RESOURCE = 0x00040004; // Name is resource name or atom. public static int SND_PURGE = 0x0040; // Purge non-static events for task. public static int SND_APPLICATION = 0x0080; // Look for application-specific association. private Thread t; // used for pausing private string bname; private int soundFlags; //----------------------------------------------------------------- public void Play(string wfname, int SoundFlags) { byte[] bname = new Byte[256]; //Max path length bname = System.Text.Encoding.ASCII.GetBytes(wfname); this.bname = bname; this.soundFlags = SoundFlags; t = new Thread(play); t.Start(); } //----------------------------------------------------------------- private void play() { PlaySound(bname, soundFlags) } public void StopPlay() { t.Stop(); } public void Pause() { t.Suspend(); // Yeah, I know it's obsolete, but it works. } public void Resume() { t.Resume(); // Yeah, I know it's obsolete, but it works. }