在Windows Phone应用程序中,我们可以将音频文件直接放到程序包里面,然后在程序中就可以通过MediaElement元素,用相对的路径进行加载音频文件来播放。
下面给出播放程序音乐的示例:播放应用程序本地加载的音乐。
代码清单8-1:播放程序音乐(源代码:第8章\Examples_8_1)
MainPage.xaml文件主要代码
------------------------------------------------------------------------------------------------------------------
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<MediaElement x:Name="sound" />
<TextBlock Text="请选择你要播放的歌曲"
FontSize="30" Height="59" HorizontalAlignment="Left" Margin="6,6,0,0" Name="textBlock1" VerticalAlignment="Top" Width="409" />
<RadioButton Content="罗志祥-Touch My Heart"
Height="72" HorizontalAlignment="Left" Margin="0,71,0,0" Name="radioButton1" VerticalAlignment="Top" Width="394" IsChecked="True" />
<RadioButton Content="陈小春-独家记忆"
Height="72" HorizontalAlignment="Left" Margin="0,149,0,0" Name="radioButton2" VerticalAlignment="Top" />
<RadioButton Content="大灿-贝多芬的悲伤"
Height="72" HorizontalAlignment="Left" Margin="0,227,0,0" Name="radioButton3" VerticalAlignment="Top" />
<RadioButton Content="筷子兄弟-老男孩"
Height="72" HorizontalAlignment="Left" Margin="0,305,0,0" Name="radioButton4" VerticalAlignment="Top" />
<RadioButton Content="梁静茹-比较爱"
Height="72" HorizontalAlignment="Left" Margin="0,383,0,0" Name="radioButton5" VerticalAlignment="Top" />
<!—播放按钮触发播放的事件-->
<Button Content="播放"
Height="72" HorizontalAlignment="Left" Margin="0,476,0,0" Name="play" VerticalAlignment="Top" Width="160" Click="play_Click" />
<!—暂停按钮触发暂停的事件-->
<Button Content="暂停"
Height="72" HorizontalAlignment="Left" Margin="135,476,0,0" Name="pause" VerticalAlignment="Top" Width="160" Click="pause_Click" />
<!—暂停按钮触发暂停的事件-->
<Button Content="停止"
Height="72" HorizontalAlignment="Left" Margin="272,476,0,0" Name="stop" VerticalAlignment="Top" Width="160" Click="stop_Click" />
</Grid>
MainPage.xaml.cs文件主要代码
------------------------------------------------------------------------------------------------------------------
//播放音乐
private void play_Click(object sender, RoutedEventArgs e)
{
//设置MediaElement的源
if (radioButton1.IsChecked==true)
{
sound.Source = new Uri("TouchMyHeart.html", UriKind.Relative);
}
else if (radioButton2.IsChecked == true)
{
sound.Source = new Uri("TouchMyHeart.html", UriKind.Relative);
}
else if (radioButton3.IsChecked == true)
{
sound.Source = new Uri("TouchMyHeart.html", UriKind.Relative);
}
else if (radioButton4.IsChecked == true)
{
sound.Source = new Uri("TouchMyHeart.html", UriKind.Relative);
}
else if (radioButton5.IsChecked == true)
{
sound.Source = new Uri("TouchMyHeart.html", UriKind.Relative);
}
else
{
sound.Source = new Uri("TouchMyHeart.html", UriKind.Relative);
}
//播放
sound.Play();
}
//暂停播放音乐
private void pause_Click(object sender, RoutedEventArgs e)
{
sound.Pause();
}
//停止播放音乐
private void stop_Click(object sender, RoutedEventArgs e)
{
sound.Stop();
}
程序运行的效果如图8.1所示。