下面是一個簡單的問題,令我驚訝的是,我找不到答案:如何在XAML中播放系統聲音?如何在XAML中播放系統聲音?
我有一個附加到按鈕的事件觸發器。觸發器顯示一條消息,我希望它播放Windows Notify聲音。我發現了幾個關於如何播放聲音文件的參考文件,但沒有提到如何調用系統聲音。
感謝您的幫助!
下面是一個簡單的問題,令我驚訝的是,我找不到答案:如何在XAML中播放系統聲音?如何在XAML中播放系統聲音?
我有一個附加到按鈕的事件觸發器。觸發器顯示一條消息,我希望它播放Windows Notify聲音。我發現了幾個關於如何播放聲音文件的參考文件,但沒有提到如何調用系統聲音。
感謝您的幫助!
SystemSounds
類提供了一些系統聲音,他們有一個Play()
方法。要在XAML中使用它,你必須使用一些拙劣的黑客,實現大量的自定義邏輯,或者使用Blend Interactivity來定義自己的TriggerAction,它可以使用SystemSound
並播放它。
的交互方法:
public class SystemSoundPlayerAction : System.Windows.Interactivity.TriggerAction<Button>
{
public static readonly DependencyProperty SystemSoundProperty =
DependencyProperty.Register("SystemSound", typeof(SystemSound), typeof(SystemSoundPlayerAction), new UIPropertyMetadata(null));
public SystemSound SystemSound
{
get { return (SystemSound)GetValue(SystemSoundProperty); }
set { SetValue(SystemSoundProperty, value); }
}
protected override void Invoke(object parameter)
{
if (SystemSound == null) throw new Exception("No system sound was specified");
SystemSound.Play();
}
}
<Window
xmlns:sysmedia="clr-namespace:System.Media;assembly=System"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
...
<Button Content="Test2">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:EventTrigger.Actions>
<local:SystemSoundPlayerAction SystemSound="{x:Static sysmedia:SystemSounds.Beep}"/>
</i:EventTrigger.Actions>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
(我不知道SystemSounds.Beep
是你正在尋找一個)
大衛Veeneman注:
對於其他r esearching這個問題,互動在回答中提到的混合要求System.Windows.Interactivity.dll,這是在C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries\
爲了完整發現了一個參考,這裏是我用來實現HB的解決標記問題。標記在狀態欄中顯示一條消息,並播放聲音System.Asterisk
。該消息包含在狀態欄中名爲StatusBarMessagePanel
的StackPanel
中。顯示該消息,然後在五秒鐘內消失。
<Button ...>
<!-- Shows, then fades status bar message. -->
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation From="1.0" To="0.0" Duration="0:0:5"
Storyboard.TargetName="StatusBarMessagePanel"
Storyboard.TargetProperty="Opacity"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
<!-- Note that the following markup uses the custom SystemSoundPlayerAction
class, which is found in the Utility folder of this project. -->
<!-- Plays the System.Asterisk sound -->
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:EventTrigger.Actions>
<local:SystemSoundPlayerAction SystemSound="{x:Static sysmedia:SystemSounds.Beep}"/>
</i:EventTrigger.Actions>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
不錯的答案!接受和+1。 – 2011-04-15 03:50:07
謝謝;實際上我在回答這個問題時自己學到了一些東西:) – 2011-04-15 03:54:15
對於研究此問題的其他人來說,答案中提到的Blend Interactivity需要參考System.Windows.Interactivity.dll,該文件位於C:\ Program Files(x86) Microsoft SDK \ Expression \ Blend \ .NETFramework \ v4.0 \ Libraries \ – 2011-04-15 10:38:24