2016-05-21 10 views
0

Wie würde ich prüfen, ob ein Sound, den ich gespielt habe, beendet ist? Ich bin für das Abspielen der Ton C# .NET WinForms und mein Code ist:Prüfen, wann der Sound fertig ist C#

SoundPlayer s = new SoundPlayer(@"c:\intro.wav"); 
     s.Play(); 

Für alle, die den Import wissen muss, es using System.Media;

So ist muss ich wissen, wenn mein Ton beendet hat Spielen, und dann muss ich etwas Code ausführen. Ich weiß, dass ich wahrscheinlich einen Timer verwenden könnte, aber ich möchte das aus bestimmten Gründen vermeiden. Vielen Dank im Voraus.

Antwort

0

Standardmäßig läuft SoundPlayer auf einem separaten Thread, aber es gibt eine Methode, um einen Sound auf dem aktuellen Thread abzuspielen. Siehe PlaySync

private SoundPlayer Player = new SoundPlayer(); 
private void loadSoundAsync() 
{ 
    // Note: You may need to change the location specified based on 
    // the location of the sound to be played. 
    this.Player.SoundLocation = "http://www.tailspintoys.com/sounds/stop.wav"; 
    this.Player.LoadAsync(); 
} 

private void Player_LoadCompleted (
      object sender, 
      System.ComponentModel.AsyncCompletedEventArgs e) 
{ 
    if (this.Player.IsLoadCompleted) 
    { 
     this.Player.PlaySync(); 
    } 
} 
2

Sie eine Aufgabe erstellen und erwarten es ohne Ihre UI-Thread blockiert ...

async void Test() 
{ 
    using (var player = new System.Media.SoundPlayer(@"C:\Windows\Media\Alarm01.wav")) 
    { 
     await Task.Run(() => { player.Load(); player.PlaySync(); }); 
     MessageBox.Show("Finished. Now you can run your code here"); 
    } 
} 
Verwandte Themen