1

我有一个非常简单的函数close(); 的退出按钮;.

我怎样才能做到这一点?声音结束(2-3 秒)应用程序关闭后。

private void button1_Click(object sender, EventArgs e)
{
// Play sound
this.playSound();

// WAIT FOR END OF SOUND

Close();
}

private void playSound()
{
            Random random = new Random();

            // Create list of quit music
            List<System.IO.UnmanagedMemoryStream> sound = new List<System.IO.UnmanagedMemoryStream>
            {
                global::Launcher.Properties.Resources.sound_quit_1,
                global::Launcher.Properties.Resources.sound_quit_2,
                global::Launcher.Properties.Resources.sound_quit_3,
                global::Launcher.Properties.Resources.sound_quit_4,
            };

            // Random, set and play sound
            (new SoundPlayer(sound[random.Next(sound.Count)])).Play();
}
4

3 回答 3

1

如果playSound()是同步的,你可以试试

private void button1_Click(object sender, EventArgs e)
{
  // Play sound
  this.playSound();
  BackgroundWorker wk = new BackGroundWorker();
  wk.RunWorkerCompleted += (s,e) => {Thread.Sleep(2000); Close(); };
  wk.RunWorkerAsync();
}

这可以防止 GUI 看起来被锁定,因为它可以使用更简单的方式

private void button1_Click(object sender, EventArgs e)
{
  // Play sound
  this.playSound();
  Thread.Sleep(2000);
  Close()
}
于 2012-11-11T16:08:46.070 回答
1
(new SoundPlayer(sound[random.Next(sound.Count)])).Play();

这将异步播放声音,因此它发生在单独的线程上。缺点是没有关于声音何时结束的信息。

您可以做的是PlaySync在单独的线程上手动使用并回调主线程,然后关闭应用程序。

于 2012-11-11T16:15:39.333 回答
0

应用程序将关闭,因为您正在播放的声音是在与主用户界面线程不同的线程中播放的。(new SoundPlayer(sound[random.Next(sound.Count)])).Play();如果您想(new SoundPlayer(sound[random.Next(sound.Count)])).PlaySync();使用用户界面 (UI) 线程播放声音,您可以随时更改。这样应用程序将等待SoundPlayer停止播放 Wave Sound 文件,然后关闭Form

例子

private void button1_Click(object sender, EventArgs e)
{
    // Play sound
    this.playSound();

    // WAIT FOR END OF SOUND

    Close();
}
private void playSound()
{
    Random random = new Random();

    // Create list of quit music
    List<System.IO.UnmanagedMemoryStream> sound = new List<System.IO.UnmanagedMemoryStream>
    {
        global::StrongholdCrusaderLauncher.Properties.Resources.sound_quit_1,
        global::StrongholdCrusaderLauncher.Properties.Resources.sound_quit_2,
        global::StrongholdCrusaderLauncher.Properties.Resources.sound_quit_3,
        global::StrongholdCrusaderLauncher.Properties.Resources.sound_quit_4,
    };

    // Random, set and play sound
    (new SoundPlayer(sound[random.Next(sound.Count)])).PlaySync(); //We've changed Play(); to PlaySync(); so that the Wave Sound file would be played in the main user interface thread
}

谢谢,
我希望你觉得这有帮助:)

于 2012-11-11T16:16:09.657 回答