Windows 8 Store Apps Learning (65) Background tasks: Background playback and control of music

Source: Internet
Author: User
Tags bool count rewind xmlns

Introduced

Re-imagine Windows 8 Store Apps after a task

Background playback and control of music

Example

An object to hold information about each piece of music

Backgroundtask/songmodel.cs


 * * * for the preservation of each piece of music related information * *
    
using System;
Using System.Threading.Tasks;
Using Windows.storage;
    
Namespace Xamldemo.backgroundtask
{public
    class Songmodel
    {
        ///<summary>
        ///music file
        ///</summary> public
        storagefile File;
    
        <summary>
        ///artist
        ///</summary> public
        string Artist;
    
        <summary>
        ///Music name
        ///</summary> public
        string Title;
    
        Public Songmodel (storagefile file)
        {
            file = file;
        }
    
        <summary>
        ///loaded Music related properties
        ///</summary> public
        async Task Loadmusicpropertiesasync ()
        {
            var properties = await this. File.Properties.GetMusicPropertiesAsync ();
    
            Artist = properties. Artist;
            Title = properties. Title;}}

Demonstrates how to perform background playback and control of music through Mediacontrol

Backgroundtask/mediacontroldemo.xaml

<page x:class= "XamlDemo.BackgroundTask.MediaControlDemo" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/
    Presentation "xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "xmlns:local=" Using:XamlDemo.BackgroundTask " Xmlns:d= "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc= "http://schemas.openxmlformats.org/ markup-compatibility/2006 "mc:ignorable=" D "> <grid background=" Transparent "> <stackpanel
    
            margin= "0 0 0" > <textblock name= "lblmsg" fontsize= "14.667"/>
            <button name= "Btnselectfiles" content= "select Files" click= "Btnselectfiles_click" margin= "0 0 0"/>
                <button name= "Btnplay" content= "Play" click= "Btnplay_click" margin= "0 0 0"/> <!-- In order for the music to play in the background, you need to set the MediaElement Audiocategory property to Backgroundcapablemedia--> <mediae Lement name= "MediaElement" Audiocategory= "Backgroundcapablemedia" autoplay= "False" mediaopened= "mediaelement_mediaopened" Mediaende 
    D= "mediaelement_mediaended" currentstatechanged= "mediaelement_currentstatechanged"/> </StackPanel> </Grid> </Page>

Backgroundtask/mediacontroldemo.cs

* * Demonstrates how to achieve background playback and control of music through Mediacontrol * * NOTE: * 1, need to add background task statement in Package.appxmanifest, and check "audio" * 2, need to MediaElement The Audiocategory property is set to Backgroundcapablemedia * * * Another: * Press the volume on the flat panel or the relevant buttons on the multimedia keyboard, pop-up background audio control box, through the Mediacontrol to monitor the user in this audio control box on the exercise
For the */using System;
Using System.Collections.Generic;
Using System.Threading.Tasks;
Using Windows.media;
Using Windows.storage;
Using Windows.Storage.Pickers;
Using Windows.Storage.Streams;
Using Windows.UI.Core;
Using Windows.UI.Xaml;
Using Windows.UI.Xaml.Controls;
    
Using Windows.UI.Xaml.Media; Namespace Xamldemo.backgroundtask {public sealed partial class Mediacontroldemo:page {private list< songmodel> _playlist = new list<songmodel> (); Background need to play the music list private int _currentsongindex = 0; Currently playing music private bool _previoustrackpressedregistered = false; Mediacontrol whether the Previoustrackpressed event is registered as private bool _nexttrackpressedregistered = false; Mediacontrol is registered NEXTTRACKPressed Event Public Mediacontroldemo () {this.
    
            InitializeComponent (); mediacontrol.playpausetogglepressed + = mediacontrol_playpausetogglepressed; Pressed the Play/pause key mediacontrol.playpressed + = mediacontrol_playpressed; Press the play key mediacontrol.pausepressed + = mediacontrol_pausepressed; Pressed the pause key mediacontrol.stoppressed + = mediacontrol_stoppressed; Press the Stop key mediacontrol.previoustrackpressed + = mediacontrol_previoustrackpressed; Pressed the "previous" key mediacontrol.nexttrackpressed + = mediacontrol_nexttrackpressed; Press the "Next" key mediacontrol.rewindpressed + = mediacontrol_rewindpressed; Press the "Fast Rewind" key mediacontrol.fastforwardpressed + = mediacontrol_fastforwardpressed; Press the "Fast Forward" key mediacontrol.soundlevelchanged + = mediacontrol_soundlevelchanged; Volume level has changed//mediacontrol.recordpressed + = mediacontrol_recordpressed;
            mediacontrol.channeldownpressed + = mediacontrol_channeldownpressed;
    
            mediacontrol.channeluppressed + = mediacontrol_channeluppressed; Mediacontrol.artistname; Currently playing the music of the artist//Mediacontrol.trackname; The name of the currently playing music//Mediacontrol.albumart; The path//Mediacontrol.isplaying of the album cover of the currently playing music; Whether the current music is playing//mediacontrol.soundlevel;
             The volume level of the currently played music (muted, low, full) _previoustrackpressedregistered = true;
        _nexttrackpressedregistered = true;
        ///press the Play/pause key on the Audio control box async void Mediacontrol_playpausetogglepressed (object sender, Object e) {if (mediacontrol.isplaying) {await dispatcher.runasync (COREDISPATCHERPR Iority.
                Normal, () => {mediaelement.pause ();
                });
         Await Outputmessage ("Play/pause pressed-pause");   else {await dispatcher.runasync (Coredispatcherpriority.normal, () =>
                {Mediaelement.play ();
                });
            Await Outputmessage ("Play/pause pressed-play");
        }///Press the play key on the audio control box async void Mediacontrol_playpressed (object sender, Object e) {await Dispatcher.runasync (Coredispatcherpriority.normal, () => {mediaelemen
            T.play ();
            });
        Await Outputmessage ("play pressed");
            ///Press the Pause key on the audio control box async void Mediacontrol_pausepressed (object sender, Object e) { Await Dispatcher.runasync (Windows.UI.Core.CoreDispatcherPriority.Normal, () => {Med
            Iaelement.pause ();
            });
        Await outputmessage ("Pause pressed"); ///press the STOP key on the audio control box async void MediacOntrol_stoppressed (object sender, Object e) {await dispatcher.runasync (Windows.UI.Core.CoreDispatcher
            Priority.normal, () => {mediaelement.stop ();
            });
        Await outputmessage ("Stop pressed"); 
            ///Press the previous key on the Audio control box async void Mediacontrol_previoustrackpressed (object sender, Object e) {
    
            Await Outputmessage ("Previous Track pressed");
                if (_currentsongindex > 0) {if (_currentsongindex = = (_playlist.count-1)) {if (!_nexttrackpressedregistered) {Mediacontrol.nextt
                        rackpressed + = mediacontrol_nexttrackpressed;
                    _nexttrackpressedregistered = true;
    
                }} _currentsongindex--; if (_currentsongindex = = 0) {mediacontrOl.
                    previoustrackpressed-= mediacontrol_previoustrackpressed;
                _nexttrackpressedregistered = false;
            } await Setcurrentplayingasync (_currentsongindex); The "Next" key on the Audio control box async void Mediacontrol_nexttrackpressed (object sender, Object E
    
            ) {await outputmessage ("Next Track pressed");
                if (_currentsongindex < (_playlist.count-1)) {_currentsongindex++;
    
                Await Setcurrentplayingasync (_currentsongindex);
                    if (_currentsongindex > 0) {if (!_previoustrackpressedregistered)
                        {mediacontrol.previoustrackpressed + = mediacontrol_previoustrackpressed;
                    _previoustrackpressedregistered = true; } if (_currentsongindex = = (_playlisT.count-1)) {if (_nexttrackpressedregistered) {
                        mediacontrol.nexttrackpressed-= mediacontrol_nexttrackpressed;
                    _nexttrackpressedregistered = false; ///pressed the "rewind" button on the Audio control box, the long press "previous" key async void Mediacontrol_rewi
        Ndpressed (object sender, Object e) {await outputmessage ("Rewind pressed");
        ///Press the "Fast-forward" button on the audio control box, that is, the "Next" key async void Mediacontrol_fastforwardpressed (object sender, Object e)
        {await outputmessage ("Fast Forward pressed");
        }//volume level changes (muted, low, full) async void Mediacontrol_soundlevelchanged (object sender, Object e)
        {await outputmessage ("Sound level Changed"); //Create a music list that needs to be played in the background private async void Btnselectfiles_click (object sender, RoutedevenTargs e) {fileopenpicker openpicker = new Fileopenpicker ();
            Openpicker.viewmode = pickerviewmode.list;
            Openpicker.suggestedstartlocation = pickerlocationid.musiclibrary;
            OpenPicker.FileTypeFilter.Add (". mp3");
            OPENPICKER.FILETYPEFILTER.ADD (". wma");
            ireadonlylist<storagefile> files = await openpicker.pickmultiplefilesasync (); if (Files.
                Count > 0) {await createplaylist (files);
            Await Setcurrentplayingasync (_currentsongindex);
        }//start playing private async void Btnplay_click (object sender, RoutedEventArgs e) {if (mediacontrol.isplaying) {await dispatcher.runasync (Coredispatcherprio Rity.
                Normal, () => {mediaelement.pause ();
                });
  Await Outputmessage ("Play/pause pressed-pause");          else {await dispatcher.runasync (Coredispatcherpriority.normal, () =&G
                T
                {Mediaelement.play ();
                });
            Await Outputmessage ("Play/pause pressed-play"); After opening the file, play the private void mediaelement_mediaopened (object sender, Ro, if required to play)
            Utedeventargs e) {if (mediacontrol.isplaying) {mediaelement.play (); After the current music is played, go to the next private async void Mediaelement_mediaended (object sender, rout Edeventargs e) {if (_currentsongindex < _playlist.count-1) {_curren
    
                tsongindex++;
    
                Await Setcurrentplayingasync (_currentsongindex);
                if (mediacontrol.isplaying) {mediaelement.play ();
       }
            } /////According to the foreground operation, set Mediacontrol isplaying Properties//View more highlights in this column: Http://www.bianceng.cnhttp://www.bianceng.cn/Pr
            ogramming/net/private void Mediaelement_currentstatechanged (object sender, RoutedEventArgs e) { if (mediaelement.currentstate = = mediaelementstate.playing) {mediacontrol.isplaying = True
                ;
            Btnplay.content = "Pause";
                else {mediacontrol.isplaying = false;
            Btnplay.content = "Play";
        }///Create music list Private Async Task createplaylist (ireadonlylist<storagefile> files) {if (_previoustrackpressedregistered) {mediacontrol.previoustrackpressed = M
                ediacontrol_previoustrackpressed;
            _previoustrackpressedregistered = false; } if (_nexttrackpressedregistered) {Mediacontrol.nexttrackpressed-= mediacontrol_nexttrackpressed;
            _nexttrackpressedregistered = false;
            } _playlist.clear ();
    
            _currentsongindex = 0; if (Files. Count > 0) {if (Files.
                    Count > 1) {mediacontrol.nexttrackpressed + = mediacontrol_nexttrackpressed;
                _nexttrackpressedregistered = true; foreach (Storagefile file in files) {Songmodel song = new song
                    Model (file); Await song.
                    Loadmusicpropertiesasync ();
                _playlist.add (song); }}//Specify the music you want to play now private async Task setcurrentplayingasync (int playli
            Stindex) {string errormessage = null;
    
            Irandomaccessstream stream = null; try {stream = await _pLaylist[playlistindex].
                File.openasync (Windows.Storage.FileAccessMode.Read); Await Dispatcher.runasync (Coredispatcherpriority.normal, () => {mediaelement.sets Ource (Stream, _playlist[playlistindex]. 
                File.contenttype);
            });
            catch (Exception e) {errormessage = E.message;
            } if (errormessage!= null) {await outputmessage (errormessage); } mediacontrol.artistname = _playlist[playlistindex].
            Artist; Mediacontrol.trackname = _playlist[playlistindex].
        Title; //Output Information private async Task Outputmessage (String message) {await Dispatcher.run Async (Coredispatcherpriority.normal, () => {lblmsg.text = message + ":" + DateTime.Now.To
            String ("Yyyy-mm-dd hh:mm:ss");
        }); }
    }
}

Ok

SOURCE Download: Http://files.cnblogs.com/webabcd/Windows8.rar

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.