2008-09-29 60 views
3

我正在寫一個Windows Forms應用程序,它應該播放三個聲音文件,並且在每個聲音文件的末尾,它將更改圖像的來源。我可以用System.Media.SoundPlayer來播放聲音。然而,它似乎在不同的線程中發揮着聲音,繼續。發出聲音,等待它完成,然後做點什麼?

這樣做的最終效果是隻播放最後一個聲音並更改所有圖像。

我試過Thread.Sleep,但它睡眠整個圖形用戶界面,睡眠期間後,一切都會立即發生並最終發出聲音。

UPDATE

我想PlaySynch是工作,但它似乎凍結我的GUI這是不太理想。我還可以做些什麼?

回答

9

你試過SoundPlayer.PlaySync Method?從幫助:

的PlaySync方法使用當前 線程播放.wav文件,防止 線程處理來自其他 消息,直到加載完成。

+0

是啊,我剛剛發現這一點,唯一的問題是,貴似乎沒有得出...會繼續做這個工作。 – 2008-09-29 13:46:40

0

你可能想要做的是做一個異步聲音,但然後禁用你的用戶界面的方式,它不響應用戶的反應。然後一旦播放聲音,您將重新啓用您的用戶界面。這將允許您仍然正常繪製UI。

0

我想出瞭如何做到這一點。我使用了PlaySynch,但是我在一個單獨的線程中完成了繪製UI的代碼。每個文件播放後,同一個線程也會更新用戶界面。

1

使用此代碼:

[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. 
} 
+2

我認爲這是嚴重矯枉過正。 – 2014-03-14 20:09:26

相關問題