0
我試圖理解在執行SoundPlayer.Play
時它不允許播放超過1個聲音異步(例如,如解釋here或here)。我看着它的source code,但我無法弄清楚。SoundPlayer.Play實現中的什麼不允許播放超過1個聲音異步?
爲了方便起見,這裏的兩個SoundPlayer.Play
和SoundPlayer.LoadAndPlay
的代碼,這是由SoundPlayer.Play
調用的方法:
public void Play() {
LoadAndPlay(NativeMethods.SND_ASYNC);
}
private void LoadAndPlay(int flags) {
//
if (String.IsNullOrEmpty(soundLocation) && stream == null) {
SystemSounds.Beep.Play();
return;
}
if (uri != null && uri.IsFile) {
// VSW 580992: With more than one thread, someone could call SoundPlayer::set_Location
// between the time LoadAndPlay demands FileIO and the time it calls PlaySound under elevation.
//
// Another scenario is someone calling SoundPlayer::set_Location between the time
// LoadAndPlay validates the sound file and the time it calls PlaySound.
// The SoundPlayer will end up playing an un-validated sound file.
// The solution is to store the uri.LocalPath on a local variable
string localPath = uri.LocalPath;
// request permission to read the file:
// pass the full path to the FileIOPermission
FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Read, localPath);
perm.Demand();
// play the path
isLoadCompleted = true;
System.Media.SoundPlayer.IntSecurity.SafeSubWindows.Demand();
System.ComponentModel.IntSecurity.UnmanagedCode.Assert();
// ValidateSoundFile calls into the MMIO API so we need UnmanagedCode permissions to do that.
// And of course we need UnmanagedCode permissions to all Win32::PlaySound method.
try {
// don't use uri.AbsolutePath because that gives problems when there are whitespaces in file names
ValidateSoundFile(localPath);
UnsafeNativeMethods.PlaySound(localPath, IntPtr.Zero, NativeMethods.SND_NODEFAULT | flags);
} finally {
System.Security.CodeAccessPermission.RevertAssert();
}
} else {
LoadSync();
ValidateSoundData(streamData);
System.Media.SoundPlayer.IntSecurity.SafeSubWindows.Demand();
System.ComponentModel.IntSecurity.UnmanagedCode.Assert();
try {
UnsafeNativeMethods.PlaySound(streamData, IntPtr.Zero, NativeMethods.SND_MEMORY | NativeMethods.SND_NODEFAULT | flags);
} finally {
System.Security.CodeAccessPermission.RevertAssert();
}
}
}
我們怎麼能知道? PlaySound被聲明爲'extern';我們在哪裏可以看到它的實施? – HeyJude
請參閱[此處](https://msdn.microsoft.com/en-us/library/windows/desktop/dd743680(v = vs.85).aspx):「SND_NOSTOP ...如果未指定此標誌, PlaySound嘗試停止當前在同一個進程中播放的聲音,其他進程播放的聲音不受影響。「 – superware