我有一个在应用程序级别运行背景音乐的应用程序,因此当用户浏览页面时音乐不会停止。但是,我也使用 VideoBrush。正如我发现的那样,我不能让两者同时运行,因为 VideoBrush 在设置其源时会崩溃。
我发现,如果在用户尝试使用 VideoBrush 时将 MediaElement 的源设置为 null,则一切正常。当然音乐停止了,这让我很懊恼,但没有发生错误。
但是,当用户从 VideoBrush 上轻按时,我试图让音乐重新开始(开始很好)但无济于事。简而言之,我无法让音乐重新开始。
这是我的代码:
应用程序.xaml
<Application.Resources>
<MediaElement x:Key="GlobalMedia" Source="minutelongsong.mp3"
MediaEnded="MediaElement_MediaEnded" Visibility="Collapsed" />
</Application.Resources>
应用程序.xaml.cs
public static MediaElement GlobalMediaElement
{
get { return Current.Resources["GlobalMedia"] as MediaElement; }
}
private void Application_Launching(object sender, LaunchingEventArgs e)
{
var AppMediaElement = App.GlobalMediaElement;
AppMediaElement.Position = TimeSpan.Zero;
AppMediaElement.Play();
}
private void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
{
var AppMediaElement = App.GlobalMediaElement;
AppMediaElement.Position = TimeSpan.Zero;
AppMediaElement.Play();
}
现在是使用 VideoBrush 的页面。
主页.xaml
<Canvas x:Name="viewfinderCanvas" Width="480" Height="800" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="Collapsed">
<Canvas.Background>
<VideoBrush x:Name="videoBrush" Stretch="Fill">
<VideoBrush.RelativeTransform>
<CompositeTransform x:Name="previewTransform"
CenterX=".5"
CenterY=".5" />
</VideoBrush.RelativeTransform>
</VideoBrush>
</Canvas.Background>
</Canvas>
MainPage.xaml.cs
private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var AppMediaElement = App.GlobalMediaElement;
AppMediaElement.Pause();
AppMediaElement.Stop();
AppMediaElement.Source = null; //set it to null to allow the cam to be set.
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary)))
{
viewfinderCanvas.Visibility = Visibility.Visible;
cam = new PhotoCamera(CameraType.Primary);
if (Orientation == PageOrientation.PortraitUp || Orientation == PageOrientation.PortraitDown || Orientation == PageOrientation.Portrait)
{
videoBrush.RelativeTransform = new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 90 };
}
videoBrush.SetSource(cam);
}
当用户通过点击屏幕按钮退出相机 VideoBrush 时,将触发此代码。它处理凸轮,并在用户允许音乐的情况下尝试再次播放音乐。但是,即使使用此代码,音乐也不会播放。
private void zoomout_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (cam != null)
{
cam.Dispose();
}
viewfinderCanvas.Visibility = Visibility.Collapsed;
if (allowingamemusic == true)
{
var AppMediaElement = App.Current.Resources["GlobalMedia"] as MediaElement;
AppMediaElement.Source = new Uri("minutelongsong.mp3", UriKind.RelativeOrAbsolute);
AppMediaElement.Position = TimeSpan.Zero;
AppMediaElement.Play(); //despite this here, it will not play. No error thrown.
}
}