soundplayer一遍又一遍地播放相同的文件

本文关键字:一遍 文件 soundplayer 播放 | 更新日期: 2023-09-27 18:15:19

我正在使用c#在我的应用程序中进行记录。

我将声音录制到同一个文件并播放它,但是SoundPlayer播放的是第一次录制的内容。

例如,我有一个文件test.wav,我记录"hello",然后我记录"hi"到同一个文件

通过覆盖文件。当我播放文件test.wav播放器播放"hello" .

我只有一个player实例,例如

public static System.Media.SoundPlayer Player;      
static void Main()
{           
    try
    {
        Player = new System.Media.SoundPlayer();
    }
    catch (Exception ex)
    {
    }
}

播放文件的代码:

public static void Play(string fileName)
{
    if (File.Exists(fileName))
    {
        Program.Player.SoundLocation = fileName;
        Program.Player.Load();
        if (Program.Player.IsLoadCompleted)
        {
            Program.Player.Play();
        }
    }
}

soundplayer一遍又一遍地播放相同的文件

SoundLocation属性的Setter中有一个有趣的检查:

set
{
    if (value == null)
    {
        value = string.Empty;
    }
    if (!this.soundLocation.Equals(value))
    {
        this.SetupSoundLocation(value);
        this.OnSoundLocationChanged(EventArgs.Empty);
    }
}

您可以看到,它会查看新位置是否与旧位置不同。如果是,那么它就做了一些准备工作。如果没有,它实际上什么也不做。

我敢打赌你可以通过这样做来解决这个问题:

public static void Play(string fileName)
{
    if (File.Exists(fileName))
    {
        Program.Player.SoundLocation = "";
        Program.Player.SoundLocation = fileName;
        Program.Player.Load();
        if (Program.Player.IsLoadCompleted)
        {
            Program.Player.Play();
        }
    }
}

第一次调用SoundLocation setter将清空加载的流。然后,第二个将再次使用位置正确地设置它,并允许Load按预期加载流。