如何在c#中设置歌曲的持续时间

本文关键字:持续时间 设置 | 更新日期: 2023-09-27 18:15:38

我有一个应用程序,它在指定的时间播放特定的歌曲,作为选择的结果。

我已经可以播放歌曲了,但是我不能设置时长。

    public void PlaySound()
    {
        int i = 0;
        foreach (string musicFile in musicFiles)
        {
            Thread thrStopMusic = new Thread(ThreadTimer);
            player.SoundLocation = musicFile;
            musicExecuteTime = GetMusicDuration[i];
            player.Play();
            thrStopMusic.Start();
            thrStopMusic.Abort();
            i++;
        }
    }
 public void ThreadTimer()
    {
       Thread.Sleep(musicExecuteTime * 1000);
       StopSound();
    }

如何在c#中设置歌曲的持续时间

也许我没有正确理解你的意图,但为什么你甚至使用一个线程来计时(我也猜StopSound()不是合适的方法来调用)?为什么不直接:

...
player.Play();
Thread.Sleep(musicExecuteTime * 1000);
player.Stop();
...

我认为你可以这样做。Play()使用一个新线程来播放文件,所以你只需要在调用Stop()之前"暂停"你的线程一段时间。

public void PlaySound()
{
    int i = 0;
    foreach (string musicFile in musicFiles)
    {
        player.SoundLocation = musicFile;
        player.Play();
        Thread.Sleep(1000 * GetMusicDuration[i])
        player.Stop();
        i++;
    }
}