A完成后启动事件B.

时间:2012-11-11 16:00:48

标签: c#

我已经退出按钮,功能非常简单 close();

我该怎么做?声音结束(2-3秒)app关闭。

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

3 个答案:

答案 0 :(得分: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()
}

答案 1 :(得分:1)

(new SoundPlayer(sound[random.Next(sound.Count)])).Play();

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

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

答案 2 :(得分:0)

应用程序将关闭,因为您正在播放的声音是在与主用户界面线程不同的线程中播放的。如果您想使用用户界面(UI)线程播放声音,则可以随时将(new SoundPlayer(sound[random.Next(sound.Count)])).Play();更改为(new SoundPlayer(sound[random.Next(sound.Count)])).PlaySync();。因此,应用程序将等待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
}

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