简体   繁体   English

SoundPlayer 第一次调用时不播放声音

[英]SoundPlayer does not play sound first time it´s called

I´ve a really simple method for playing sound effects:我有一个非常简单的播放音效的方法:

private void PlaySound(string file){
   SoundPlayer sp = new SoundPlayer(@"Effects\" + file ' ".wav");
   sp.Play();

}

Then I do this do call it:然后我这样做确实称之为:

PlaySound("music"); PlaySound("音乐");

Now, the first time PlaySound("music") gets called, it won´t play it.现在,第一次调用 PlaySound("music") 时,它不会播放。 The second time and all the other time after that it will.第二次和之后的所有其他时间都会。

Any ideas of what goes wrong here?关于这里出了什么问题的任何想法?

Try this:尝试这个:

private void PlaySound(string file){
   using (SoundPlayer player = new SoundPlayer(@"Effects\" + file ' ".wav"))
    {
        // Use PlaySync to load and then play the sound.
        player.PlaySync();
    }
}

Why use PlaySync?为什么要使用 PlaySync? If you just call the Play method in this program, the program will terminate before the sound plays.如果你只是在这个程序中调用 Play 方法,程序将在声音播放之前终止。 The Sync indicates that the program should pause while the sound plays.同步指示程序应在声音播放时暂停。

You need to call the load method before playing.If the the file is not already loaded ,the file will be loaded with a call to Play .Which explains why the file is not played the first time.你需要在播放前调用load方法。如果文件还没有加载,文件将通过调用Play加载。这解释了为什么第一次没有播放文件。

If you call Play before the .wav file has been loaded into memory, the .wav file will be loaded before playback starts.如果在 .wav 文件加载到内存之前调用 Play ,则 .wav 文件将在播放开始之前加载。 -MSDN -MSDN

Both Load and PlaySync will block the current thread.A better option would be to use the LoadAsync to load the file asynchronously. LoadPlaySync都会阻塞当前线程。更好的选择是使用LoadAsync异步加载文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM