Windows 8.1背景音频播放器无法在应用程序的其他页面中运行

时间:2014-08-28 12:32:36

标签: c# windows audio windows-8.1

我有一个应用程序,它将从互联网流式传输音频,媒体元素位于主页面,它可以正常工作,而应用程序在后台,我在应用程序中有多个页面,而导航从主页面到另一页面,当我回到主页面时,音频停止并恢复工作 有没有办法使它适用于应用程序中的其他页面?

1 个答案:

答案 0 :(得分:0)

我为Windows和Windows手机编写音板。

为包含媒体元素的框架创建App范围样式。现在帧可以播放声音,在页面之间导航不会影响声音。

现在媒体元素在框架上,页面需要以某种方式引用该媒体元素。我创建了一个公共课来帮助。然后每个页面都注册到这个类来播放声音。

在页面中:

SoundPlayer.Instance.Initialize();

SoundPlayer类:

public void Initialize()
    {
        // Register media elements to the Sound Service.
        try
        {
            DependencyObject rootGrid = VisualTreeHelper.GetChild(Window.Current.Content, 0);
            var foregroundPlayer = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 0) as MediaElement;
            var backgroundPlayer = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 1) as MediaElement;

            SoundPlayer.ForegroundPlayer = foregroundPlayer;

            // Keep the state.
            var isMuted = this.IsBackgroundMuted;
            SoundPlayer.BackgroundPlayer = backgroundPlayer;
            this.IsBackgroundMuted = isMuted;
        }
        catch (Exception)
        {
            // Most probably you forgot to apply the custom root frame style.
            SoundPlayer.ForegroundPlayer = null;
            SoundPlayer.BackgroundPlayer = null;
        }
    }


    public async Task Play(string soundPath, bool inBackground = false)
    {
        var mediaElement = inBackground ? BackgroundPlayer : ForegroundPlayer;

        if (mediaElement == null)
        {
            return;
        }

        mediaElement.Source = new Uri(soundPath);

        await mediaElement.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            mediaElement.Stop();
            mediaElement.Play();
        });
    }

在App.xaml中

<ResourceDictionary>
                <Style x:Key="RootFrameStyle"
                       TargetType="Frame">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="Frame">
                                <Grid>
                                    <!-- Foreground Player -->
                                    <MediaElement IsLooping="False" />
                                    <!-- Background Player -->
                                    <MediaElement IsLooping="True" />
                                    <Grid>
                                        <ContentPresenter />
                                    </Grid>
                                </Grid>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ResourceDictionary>

这是一篇博文,更详细地解释了这一点。 http://blogs.u2u.be/diederik/post/2014/07/10/Playing-sounds-in-a-Universal-Windows-MVVM-app.aspx