這段時間我們小組要給部門的Annual Meeting準備一個WPF的抽獎程序,為了增加程序的有趣性,我們在程序中需要播放背景音樂等。由於對之前從未使用過WPF,所以對其中的聲音等媒體文件播放不是很清楚,對一些簡單的問題也花了相對較長的時間去解決,現在將其總結在下麵,以供大家參考。
1,使用SoundPlayer類
SoundPlayer類位於System.Media命名空間下,它只能播放.wav格式的聲音文件。其使用方法簡單如下:
- using(SoundPlayer player = new SoundPlayer())
- {
- string location=System.Environment.CurrentDirectory+"//Sounds//explosion.wav";
- player.SoundLocation=location;
- player.Play();
- }
上面的代碼段即是播放主程序文件夾內下的Sounds文件夾下的explosion.wav聲音文件。如果你的聲音文件比較小,可以直接作為資源嵌入到應用程序中,這裡的Location屬性使用相對路徑即可。
除了上面提到的文件格式限制外,這個類還有個缺陷,就是你只能同時播放一個聲音文件,即便你實例化幾個不同的類,在我的程序中最初考慮一個背景音樂文件一直循環播放,可是當我把光標放置於另外一個我自己定制的UserControl上,會播放一個聲音,而之前的背景音樂就會消失,於是我不得不用其它的方法。
2,使用MediaPlayer類
MediaPlayer類位於System.Windows.Media命名空間下,關於此類詳情參考http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer(v=VS.100).aspx。
如下示例:
- MediaPlayer player = new MediaPlayer();
- player.Open(new Uri(@"sampleMedia/xbox.wmv", UriKind.Relative));
- VideoDrawing aVideoDrawing = new VideoDrawing();
- aVideoDrawing.Rect = new Rect(0, 0, 100, 100);
- aVideoDrawing.Player = player;
- player.Play();
3,在XAML中使用MediaPlayer元素
MediaPlayer元素可以方便的在XAML中直接使用MediaPlayer,如下示例:
- <MediaElement Name="MyMediaElement">
- <MediaElement.Triggers>
- <EventTrigger RoutedEvent="MediaElement.Loaded">
- <EventTrigger.Actions>
- <BeginStoryboard>
- <Storyboard>
- <MediaTimeline x:Name="mediatiemline" Source=<span style="color: #a31515;">"pack://siteoforigin:,,,/Sounds/test.mp3"</span> Storyboard.TargetName="MyMediaElement"
- RepeatBehavior="Forever" />
- </Storyboard>
- </BeginStoryboard>
- </EventTrigger.Actions>
- </EventTrigger>
- </MediaElement.Triggers>
- </MediaElement>
以上示例是在加載時MediaElement循環播放音樂文件。
請注意Source="pack://siteoforigin:,,,/Sounds/test.mp3" 這裡的路徑表示方法,亦可以直接在Code-behind中直接設置:
我們可以發現,通過MediaPlayer可以解決文件格式限制問題,還可以解決不能同時播放幾個聲音的問題。
- this.mediatiemline.Source=new Uri(<span style="background-color: #ffff00;">Environment.CurrentDirectory </span>+ <a><span style="color: #4c7d08;">//Sounds//test.mp3</span></a>);
- ps:<span style="background-color: #ffff00;"><span style="color: #ff0000;">Environment.CurrentDirectory:<span style="background-color: #ffffff;">獲取或設置當前工作目錄的完全限定路徑。這個就解決了相對路徑的問題。</span></span></span>
4,使用MediaPlayer(包括MediaElement)的注意事項
我們在測試的時候發現,由於電腦上Windows Media Player的版本比較低,導致在播放一些音樂文件的時候出問題,沒有聲音,我們花費了很長時間解決代碼的問題,最終發現問題是在Windows Media Player版本上,所以如果大家遇到類似問題請記得更新你的Windows Media Player為較高版本,XP系統可以在這裡下載11.0版本:
文章列表