在 Windows Phone 7 中获取媒体播放器状态 [英] Getting media player state in windows phone 7

查看:28
本文介绍了在 Windows Phone 7 中获取媒体播放器状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 App.xaml.cs

中修改了我的代码

但我在 "this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));" 处有错误(放置在我的 App.xaml.cs 末尾)>

错误是

  • System.TimeSpan.FromMilliseconds(double) 是一种方法,但像类型一样使用"
  • System.Windows.Application.ApplicationLifetimeObjects 是一个属性,但像类型一样使用
  • 需要标识符
  • 类、结构或接口成员声明中的无效标记("
  • 方法必须有返回类型

以下是我的 App.xaml.cs 的全部内容

命名空间 Alarm_Clock{公共类 GlobalData{public BitmapImage bitmapImage;}公共部分类 App : 应用程序{公共静态 GlobalData globalData;公共类 XNAAsyncDispatcher : IApplicationService{私有只读 DispatcherTimer _frameworkDispatcherTimer;公共 XNAAsyncDispatcher(TimeSpan dispatchInterval){_frameworkDispatcherTimer = new DispatcherTimer();_frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;_frameworkDispatcherTimer.Interval = dispatchInterval;}void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start();}无效 IApplicationService.StopService() { _frameworkDispatcherTimer.Stop();}void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update();}}公共静态字符串 imagePath{//get { return "PhotoNote_{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg";}得到;放;}///<总结>///提供对电话应用程序根框架的轻松访问.///</总结>///<returns>电话应用程序的根框架.</returns>公共 PhoneApplicationFrame RootFrame { 获取;私人订制;}//整个应用程序中使用的WriteableBitmap对象的全局变量.公共静态 WriteableBitmap CapturedImage;///<总结>///Application 对象的构造函数.///</总结>公共应用程序(){globalData = new GlobalData();globalData.bitmapImage = new BitmapImage();//未捕获异常的全局处理程序.UnhandledException += Application_UnhandledException;//调试时显示图形分析信息.如果(System.Diagnostics.Debugger.IsAttached){//显示当前帧速率计数器.Application.Current.Host.Settings.EnableFrameRateCounter = true;//显示每帧中正在重绘的应用程序区域.//Application.Current.Host.Settings.EnableRedrawRegions = true;//启用非生产分析可视化模式,//用彩色叠加显示页面中 GPU 加速的区域.//Application.Current.Host.Settings.EnableCacheVisualization = true;}//标准 Silverlight 初始化初始化组件();//手机特定的初始化InitializePhoneApplication();}//应用程序启动时执行的代码(例如,从开始)//重新激活应用程序时不会执行此代码私有无效Application_Launching(对象发送者,LaunchingEventArgs e){}//当应用程序被激活时执行的代码(带到前台)//当应用程序第一次启动时,这段代码不会执行私有无效Application_Activated(对象发送者,ActivatedEventArgs e){}//应用程序停用时执行的代码(发送到后台)//当应用程序关闭时,这段代码不会执行私有无效Application_Deactivated(对象发送者,DeactivatedEventArgs e){}//当应用程序关闭时执行的代码(例如,用户回击)//当应用程序被停用时,此代码将不会执行私有无效Application_Closing(对象发送者,ClosingEventArgs e){}//导航失败时执行的代码私人无效RootFrame_NavigationFailed(对象发送者,NavigationFailedEventArgs e){如果(System.Diagnostics.Debugger.IsAttached){//导航失败;闯入调试器System.Diagnostics.Debugger.Break();}}//对未处理异常执行的代码私有无效Application_UnhandledException(对象发送者,ApplicationUnhandledExceptionEventArgs e){如果(System.Diagnostics.Debugger.IsAttached){//发生了未处理的异常;闯入调试器System.Diagnostics.Debugger.Break();}}#region 手机应用初始化//避免双重初始化private bool phoneApplicationInitialized = false;//不要向这个方法添加任何额外的代码私有无效 InitializePhoneApplication(){如果(电话应用程序初始化)返回;//创建框架,但不要将其设置为 RootVisual;这允许飞溅//屏幕保持活动状态,直到应用程序准备好呈现.RootFrame = new PhoneApplicationFrame();RootFrame.Navigated += CompleteInitializePhoneApplication;//处理导航失败RootFrame.NavigationFailed += RootFrame_NavigationFailed;//确保我们不会再次初始化phoneApplicationInitialized = true;}//不要向这个方法添加任何额外的代码private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e){//设置根视觉以允许应用程序呈现如果(RootVisual != RootFrame)RootVisual = RootFrame;//删除此处理程序,因为不再需要它RootFrame.Navigated -= CompleteInitializePhoneApplication;}#endregionthis.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));}

}

暂停在我下面的代码中不起作用.

这是我的全部代码:

命名空间 Alarm_Clock{公共部分类 AlarmRing : PhoneApplicationPage{int SongSelectedIndex;公共报警环(){初始化组件();SupportedOrientations = SupportedPageOrientation.Portrait;//获取DateTime.Now并将其放入timeTxtBlock"文本块timeTxtBlock.Text = DateTime.Now.ToShortTimeString();//从Isolated storage queSetting.txt中读取用户回答的问题数//从Isolated storage music.txt中读取闹钟响起时播放的选定音乐var isoFile = IndependentStorageFile.GetUserStoreForApplication();隔离存储文件 myStore = 隔离存储文件.GetUserStoreForApplication();尝试{StreamReader readFile = new StreamReader(new IndependentStorageFileStream("SettingFolder\\music.txt", FileMode.Open, myStore));SongSelectedIndex = Convert.ToInt16(readFile.ReadLine());readFile.Close();}捕获(异常){//如果用户在闹钟响起时没有选择要播放的音乐,则默认播放第一首音乐歌曲选择索引 = 0;}使用 (var ml = new MediaLibrary()){//使用歌曲集中的媒体播放器播放音乐FrameworkDispatcher.Update();MediaPlayer.MediaStateChanged += new EventHandler(MediaPlayer_MediaStateChanged);MediaPlayer.Play(ml.Songs[songSelectedIndex]);MediaPlayer.IsRepeating = true;MediaPlayer.IsMuted = false;MediaPlayer.IsShuffled = false;MediaPlayer.IsVisualizationEnabled = false;}//加载代码加载时间();}静态无效 MediaPlayer_MediaStateChanged(对象发送者,EventArgs e){如果(MediaPlayer.State == MediaState.Paused){MediaPlayer.Resume();}}无效加载时间(){ringingAlarm.Begin();//获取DateTime.NowString timeNow = DateTime.Now.ToShortTimeString();使用(IsolatedStorageFile 存储=IsolatedStorageFile.GetUserStoreForApplication()){foreach (storage.GetFileNames("*") 中的字符串标签){XElement _xml;IndependentStorageFileStream location = new IndependentStorageFileStream(labels, System.IO.FileMode.Open, storage);System.IO.StreamReader file = new System.IO.StreamReader(location);_xml = XElement.Parse(file.ReadToEnd());if (_xml.Name.LocalName != null){XAttribute time = _xml.Attribute("time");//获取星期几String dayOfWeek = DateTime.Now.DayOfWeek.ToString("F");if (timeNow == time.Value.ToString()){//textBlock2"文本块将显示报警标签textBlock2.Text = 标签;}}文件.处置();location.Dispose();}}}字符串设置查询;字符串设置QuesPassToGame;字符串格式;字符串格式1;protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e){base.OnNavigatedTo(e);//尝试从setClockPage.xaml中获取用户要回答的问题数量的值if (NavigationContext.QueryString.TryGetValue("settingQues", out settingQues))settingQuesPassToGame = settingQues;//尝试获取传递过来的格式if (NavigationContext.QueryString.TryGetValue("format", out format))格式 1 = 格式;}//显示一个带有说明的弹出消息框//并导航到Start.xaml"私人无效gameBtn_Click(对象发送者,RoutedEventArgs e){MessageBox.Show("解除警报" + System.Environment.NewLine + "- 回答选定的 IQ 问题" + System.Environment.NewLine + "- 所有正确答案");NavigationService.Navigate(new Uri("/Start.xaml?ringingAlarmTitle=" + textBlock2.Text + "&ringingAlarmTime=" + timeTxtBlock.Text + "&format1=" + format1, UriKind.Relative));}protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e){e.取消=真;}公共可见性可见{获取;放;}}}

当我在构造函数中放置 MediaPlayer.MediaStateChanged += new EventHandler(MediaPlayer_MediaStateChanged); 时出现错误.

错误是 MediaPlayer.MediaStateChanged += new EventHandler(MediaPlayer_MediaStateChanged) 是一种方法,但像类型一样使用.

<小时>

我已经更改了我的代码,但它仍然不起作用

static void MediaPlayer_MediaStateChanged(object sender, EventArgs e){如果(MediaPlayer.State == MediaState.Paused){MediaPlayer.Resume();}}

解决方案

您必须在 Windows Phone 7 应用程序中发送 XNA 事件手册:

公共类 XNAAsyncDispatcher : IApplicationService{私有只读 DispatcherTimer _frameworkDispatcherTimer;公共 XNAAsyncDispatcher(TimeSpan dispatchInterval){_frameworkDispatcherTimer = new DispatcherTimer();_frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;_frameworkDispatcherTimer.Interval = dispatchInterval;}void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start();}无效 IApplicationService.StopService() { _frameworkDispatcherTimer.Stop();}void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update();}}

将此添加到您的public App()

的末尾

公共应用程序(){//其他的东西//结尾this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));}

完整指南:http://msdn.microsoft.com/library/ff842408.aspx

I have amended my code in App.xaml.cs

But i have an error at "this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));" (Placed at end of my App.xaml.cs)

The error is

  • "System.TimeSpan.FromMilliseconds(double) is a method but is used like a type"
  • System.Windows.Application.ApplicationLifetimeObjects is a property but is used like a type
  • Identifier expected
  • Invalid token '(' in a class, struct or interface member declaration
  • Method must have a return type

Below is the whole piece of my App.xaml.cs

namespace Alarm_Clock

{

public class GlobalData

{
    public BitmapImage bitmapImage;
} 

public partial class App : Application
{
    public static GlobalData globalData;

    public class XNAAsyncDispatcher : IApplicationService
{
    private readonly DispatcherTimer _frameworkDispatcherTimer;

    public XNAAsyncDispatcher(TimeSpan dispatchInterval)
    {
        _frameworkDispatcherTimer = new DispatcherTimer();
        _frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
        _frameworkDispatcherTimer.Interval = dispatchInterval;
    }
    void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start(); }
    void IApplicationService.StopService() { _frameworkDispatcherTimer.Stop(); }
    void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
}

    public static string imagePath
    {
        //get { return "PhotoNote_{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg"; }
        get;
        set;
    }

    /// <summary>
    /// Provides easy access to the root frame of the Phone Application.
    /// </summary>
    /// <returns>The root frame of the Phone Application.</returns>
    public PhoneApplicationFrame RootFrame { get; private set; }

    //Global variables for the WriteableBitmap objects used throughout the application.
    public static WriteableBitmap CapturedImage;

    /// <summary>
    /// Constructor for the Application object.
    /// </summary>
    public App()
    {
        globalData = new GlobalData();
        globalData.bitmapImage = new BitmapImage(); 

        // Global handler for uncaught exceptions. 
        UnhandledException += Application_UnhandledException;

        // Show graphics profiling information while debugging.
        if (System.Diagnostics.Debugger.IsAttached)
        {
            // Display the current frame rate counters.
            Application.Current.Host.Settings.EnableFrameRateCounter = true;

            // Show the areas of the app that are being redrawn in each frame.
            //Application.Current.Host.Settings.EnableRedrawRegions = true;

            // Enable non-production analysis visualization mode, 
            // which shows areas of a page that are being GPU accelerated with a colored overlay.
            //Application.Current.Host.Settings.EnableCacheVisualization = true;
        }

        // Standard Silverlight initialization
        InitializeComponent();

        // Phone-specific initialization
        InitializePhoneApplication();
    }

    // Code to execute when the application is launching (eg, from Start)
    // This code will not execute when the application is reactivated
    private void Application_Launching(object sender, LaunchingEventArgs e)
    {
    }

    // Code to execute when the application is activated (brought to foreground)
    // This code will not execute when the application is first launched
    private void Application_Activated(object sender, ActivatedEventArgs e)
    {
    }

    // Code to execute when the application is deactivated (sent to background)
    // This code will not execute when the application is closing
    private void Application_Deactivated(object sender, DeactivatedEventArgs e)
    {
    }

    // Code to execute when the application is closing (eg, user hit Back)
    // This code will not execute when the application is deactivated
    private void Application_Closing(object sender, ClosingEventArgs e)
    {
    }

    // Code to execute if a navigation fails
    private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
    {
        if (System.Diagnostics.Debugger.IsAttached)
        {
            // A navigation has failed; break into the debugger
            System.Diagnostics.Debugger.Break();
        }
    }

    // Code to execute on Unhandled Exceptions
    private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
        if (System.Diagnostics.Debugger.IsAttached)
        {
            // An unhandled exception has occurred; break into the debugger
            System.Diagnostics.Debugger.Break();
        }
    }

    #region Phone application initialization

    // Avoid double-initialization
    private bool phoneApplicationInitialized = false;

    // Do not add any additional code to this method
    private void InitializePhoneApplication()
    {
        if (phoneApplicationInitialized)
            return;

        // Create the frame but don't set it as RootVisual yet; this allows the splash
        // screen to remain active until the application is ready to render.
        RootFrame = new PhoneApplicationFrame();
        RootFrame.Navigated += CompleteInitializePhoneApplication;

        // Handle navigation failures
        RootFrame.NavigationFailed += RootFrame_NavigationFailed;

        // Ensure we don't initialize again
        phoneApplicationInitialized = true;
    }

    // Do not add any additional code to this method
    private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
    {
        // Set the root visual to allow the application to render
        if (RootVisual != RootFrame)
            RootVisual = RootFrame;

        // Remove this handler since it is no longer needed
        RootFrame.Navigated -= CompleteInitializePhoneApplication;
    }

    #endregion
    this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}

}

The pause just dont work in my code below.

This is my whole piece of code:

namespace Alarm_Clock
{

    public partial class AlarmRing : PhoneApplicationPage
    {
        int songSelectedIndex;

        public AlarmRing()
        {
            InitializeComponent();
            SupportedOrientations = SupportedPageOrientation.Portrait;
            //Get the DateTime.Now and place it into "timeTxtBlock" text block
            timeTxtBlock.Text = DateTime.Now.ToShortTimeString();


            //Read from Isolated storage queSetting.txt for the number of question to answer by the user
            //Read from Isolated storage music.txt for the selected music to play when the alarm ring
            var isoFile = IsolatedStorageFile.GetUserStoreForApplication();

                IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
                try
                {
                    StreamReader readFile = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\music.txt", FileMode.Open, myStore));

                    songSelectedIndex = Convert.ToInt16(readFile.ReadLine());
                    readFile.Close();
                }
                catch (Exception)
                {
                    //If the user did not select the music to be played when the alarm ring it will play the first music by default
                    songSelectedIndex = 0;
                }


            using (var ml = new MediaLibrary())
            {
                //Play the music using media player from the song collection
                FrameworkDispatcher.Update();
                MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);
                MediaPlayer.Play(ml.Songs[songSelectedIndex]);
                MediaPlayer.IsRepeating = true;
                MediaPlayer.IsMuted = false;
                MediaPlayer.IsShuffled = false;
                MediaPlayer.IsVisualizationEnabled = false;

            }

            //Load code
            loadtime();
        }

        static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
        {
            if (MediaPlayer.State == MediaState.Paused)
            {
                MediaPlayer.Resume();
            }

        }

        void loadtime()
        {
            ringingAlarm.Begin();

            //Get the DateTime.Now
            String timeNow = DateTime.Now.ToShortTimeString();


            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                foreach (string labels in storage.GetFileNames("*"))
                {
                    XElement _xml;
                    IsolatedStorageFileStream location = new IsolatedStorageFileStream(labels, System.IO.FileMode.Open, storage);
                    System.IO.StreamReader file = new System.IO.StreamReader(location);
                    _xml = XElement.Parse(file.ReadToEnd());
                    if (_xml.Name.LocalName != null)
                    {
                        XAttribute time = _xml.Attribute("time");
                        //Get the day of the week
                        String dayOfWeek = DateTime.Now.DayOfWeek.ToString("F");

                        if (timeNow == time.Value.ToString())
                        {
                            //"textBlock2" text block will display the label of the alarm
                            textBlock2.Text = labels;
                        }
                    }
                    file.Dispose();
                    location.Dispose();
                }

            }

        }

        string settingQues;
        string settingQuesPassToGame;
        string format;
        string format1;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            //Try get the value of number of question to be answered by the user that is pass over from setClockPage.xaml
            if (NavigationContext.QueryString.TryGetValue("settingQues", out settingQues))
                settingQuesPassToGame = settingQues;

            //Try get the format that is passed over
            if (NavigationContext.QueryString.TryGetValue("format", out format))
                format1 = format;
        }

        //Display a pop up message box with instruction
        //And navigate to "Start.xaml"
        private void gameBtn_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("To dismiss alarm" + System.Environment.NewLine + "- Answer selected IQ question" + System.Environment.NewLine + "- With all correct answer");
            NavigationService.Navigate(new Uri("/Start.xaml?ringingAlarmTitle=" + textBlock2.Text + "&ringingAlarmTime=" + timeTxtBlock.Text + "&format1=" + format1, UriKind.Relative));
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
        }

        public Visibility visible { get; set; }
    }
}    

When I place MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged); at the constructor there is an error.

The error is MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged) is a method but is use like a type.


I have changed my code but it still dosent work

static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{

 if (MediaPlayer.State == MediaState.Paused) 
 {
     MediaPlayer.Resume();
 }

}

解决方案

You have to dispatch XNA Events manual in Windows Phone 7 Apps:

public class XNAAsyncDispatcher : IApplicationService
{
    private readonly DispatcherTimer _frameworkDispatcherTimer;

    public XNAAsyncDispatcher(TimeSpan dispatchInterval)
    {
        _frameworkDispatcherTimer = new DispatcherTimer();
        _frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
        _frameworkDispatcherTimer.Interval = dispatchInterval;
    }

    void IApplicationService.StartService(ApplicationServiceContext context) { _frameworkDispatcherTimer.Start(); }
    void IApplicationService.StopService() { _frameworkDispatcherTimer.Stop(); }
    void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
}

Add this to the end of your public App()

public App()
{
    // Other stuff

    // End
    this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}

Complete Guide: http://msdn.microsoft.com/library/ff842408.aspx

这篇关于在 Windows Phone 7 中获取媒体播放器状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆