在Windows Phone 7中获取媒体播放器状态

时间:2011-08-12 00:34:16

标签: c# 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

的整个部分
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)));
}

}

暂停只是在我的代码中不起作用。

这是我的整段代码:

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; }
    }
}    

当我在构造函数中放置MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);时会出错。

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


我已更改了我的代码,但仍然无法正常工作

static void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{

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

}

1 个答案:

答案 0 :(得分:1)

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

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 App()

的末尾
public App()
{
    // Other stuff

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

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