MP3 played in separate thread
One problem was solved, another followed: In a C#-program I use following method to set a labels color to green, then playing a mp3-file and finally setting the color back to black. The problem is that the sound seems to be played in an extra thread, thus the time between the change of the two colors is t开发者_如何学Pythonoo short (in fact, it should have the green color while the file is played).
private void playSound()
{
label1.ForeColor = Color.LimeGreen;
Application.DoEvents();
WMPLib.WindowsMediaPlayer wmp = new WMPLib.WindowsMediaPlayer();
wmp.URL = @"C:\examplesound.mp3"; // duration about 30s
wmp.controls.play();
label1.ForeColor = Color.Black;
}
Is there anything can be done to force the label to keep the green color whilst the mp3-file is played?
Don't set the colour back to black straight away as the playback is in another thread.
When the current track ends WMPLib sends out a PlayStateChange
event.
So add a handler:
wmp.PlayStateChange += this.Player_PlayStateChange;
private void Player_PlayStateChange(int newState)
{
if ((WMPLib.WMPPlayState)newState == WMPLib.WMPPlayState.wmppsStopped)
{
label1.ForeColor = Color.Black;
}
}
The page for playState
has a list of values:
8 - MediaEnded - Media item has completed playback.
You'll need to make sure this is done on the UI thread.
Try hooking the PlayStateChanged event and put the label1.ForeColor = Color.Black;
in there.
At the moment there's nothing in your code saying that it should only change to black when it finishes, only after it has started to play.
精彩评论