MP3 在单独的线程中播放

发布于 2024-10-19 17:28:17 字数 514 浏览 6 评论 0原文

一个问题解决了,另一个问题随之而来:在 C# 程序中,我使用以下方法将标签颜色设置为绿色,然后播放 mp3 文件,最后将颜色设置回黑色。 问题是声音似乎是在额外的线程中播放的,因此两种颜色变化之间的时间太短(事实上,在播放文件时它应该具有绿色)。

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

有什么办法可以强制标签在播放 mp3 文件时保持绿色吗?

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 too 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╭⌒浅淡时光〆 2024-10-26 17:28:17

不要立即将颜色设置回黑色,因为播放是在另一个线程中进行的。

当当前曲目结束时,WMPLib 会发出 PlayStateChange 事件。

因此,添加一个处理程序:

wmp.PlayStateChange += this.Player_PlayStateChange;

private void Player_PlayStateChange(int newState)
{
    if ((WMPLib.WMPPlayState)newState == WMPLib.WMPPlayState.wmppsStopped)
    {
        label1.ForeColor = Color.Black;
    }
}

的页面playState 有一个值列表:

8 - MediaEnded - 媒体项目已完成播放。

您需要确保这是在 UI 线程上完成的。

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.

舞袖。长 2024-10-26 17:28:17

尝试挂钩 PlayStateChanged 事件并将 label1.ForeColor = Color.Black; 放入其中。

目前,您的代码中没有任何内容表明它只应在完成时、仅在开始播放后更改为黑色。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文