New Fashion Windows 8 Development (26): Background playback musics

Source: Internet
Author: User

The Windows Store application is like a web page and full screen. Therefore, this is obviously different from the traditional desktop application. At the same time, only one application runs on the foreground, yes, just like a mobile phone.

Today, our topic is essentially about media playback. However, if you don't consider background playback, it feels a bit ...... You think, when you start a music playing app that is listening to pretty music, suddenly I want to see what updates are available on my Weibo, return to the "Start" screen and start the Weibo app. Rely on me! The music stops. You think that's boring.

Therefore, when we want to develop a music playing application, it is a top priority to support Background playback.

 

All right, the cowhide won't be blown up, so I started to answer the question.

You should know how to play multimedia in the application. Of course, I am referring to XAML. HTML5 itself supports multimedia playback. Yes, mediaelement. Remember it, this old man, you cannot not know D. You must have been in close contact with her during development such as WPF, Silverlight, and Windows Phone. This control is easy to use. Just give her a stream play source, just like a well-performing mm. You just need to make a simple dress for her and play it on the stage.

<MediaElement Source="abcd.mp3" />

You may set the volume or something or set autoplay to true, so that the control can be played immediately after the source is set.

 

This, I believe everyone will, and there will be more than one repeat here, or someone else will say, "This has a hairy relationship with Win8. Isn't this the XAML in WPF ?" Yes, XAML is good, cross-project application; perfect integration is good, learn a knowledge, can quickly migrate to other knowledge; uniformity is good, focus on program, you don't have to worry about conflicts or other issues.

So, how can we achieve background playback? Let's do an experiment. I will omit how to create a new project. I believe this operation will even happen to the ostrich.

1. Open the configuration file editor, switch to the "functions" tab, and select "music library". We will use it later.

 

2. Switch to the "Declaration" tab, select "background task" from the drop-down list, and click "add". Then, select "audio" in the right pane ", and fill in the entry point. The default value is app.

 

3. Open the XAML file of the home page and complete the UI layout.

<Page X: class = "backgroundaudioexample. mainpage "xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "xmlns: Local =" using: backgroundaudioexample "xmlns: D =" http://schemas.microsoft.com/expression/blend/2008 "xmlns: MC =" http://schemas.openxmlformats.org/markup-compatibility/2006 "MC: ignorable = "D"> <grid background = "{staticresource applicationpagebackgroundthemebrush}"> <stackpanel margin = "28"> <textblock margin = "2, 1, "textwrapping =" Wrap "> <span fontsize =" 24 "fontweight =" bold "> background playback must meet the following conditions: </span> <linebreak/> <run fontsize = "20"> in the configuration file, declaration of adding background tasks </run> <linebreak/> <run fontsize = "20"> it is best to have a multimedia control key on the keyboard of your PC or notebook, this makes it easy to </run> <linebreak/> <run fontsize = "20" foreground = "blue"> set the audiocategory attribute of mediaelement to backgroundcapablemedia or communications </run> <linebreak/> <run fontsize = "20"> Register a mediacontrol Control event </run> </textblock> <stackpanel orientation = "horizontal" margin = "3, 4, 3, 0 "> <button content =" select audio file "Click =" onselectfile "/> <button X: name = "btnplayorpause" content = "play" Click = "onplayorpause" margin = "12, 0, 0, 0 "/> <button content =" stop "Click =" onstop "margin =" 8, 0, 0 "/> <textblock X: Name =" tbmessage "margin =" 30, 0, 0, 0 "/> </stackpanel> <mediaelement X: name = "mymediaelement" width = "0" Height = "0" opacity = "0" audiocategory = "backgroundcapablemedia" autoplay = "false" currentstatechanged = "success" mediafailed = "fail" mediaended = "mymediaelement_mediaended_1" mediaopened = "mymediaelement_mediaopened_1"/> </GRID> </Page>

 

4. Switch the Code view. There are several events to handle.

Using system; using system. collections. generic; using system. io; using system. LINQ; using Windows. foundation; using Windows. foundation. collections; using Windows. UI. XAML; using Windows. UI. XAML. controls; using Windows. UI. XAML. controls. primitives; using Windows. UI. XAML. data; using Windows. UI. XAML. input; using Windows. UI. XAML. media; using Windows. UI. XAML. navigation; // introduce the following namespace using Windows. media; using Windows. sto Rage; using Windows. storage. pickers; using Windows. storage. streams; namespace backgroundaudioexample {public sealed partial class mainpage: Page {public mainpage () {This. initializecomponent ();} private string musictitle = string. empty; // music title private string musicartist = string. empty; // artist private void mymediaelement_currentstatechanged_1 (Object sender, routedeventargs e) {Switch (this. mymediaele Ment. currentstate) {Case mediaelementstate. Buffering: tbmessage. Text = "loading. "; Break; Case mediaelementstate. Closed: tbmessage. Text =" disabled. "; Mediacontrol. isplaying = false; break; Case mediaelementstate. Opening: tbmessage. Text =" the media is being opened. "; Break; Case mediaelementstate. paused: mediacontrol. isplaying = false; tbmessage. Text =" paused. "; Btnplayorpause. content =" playing "; break; Case mediaelementstate. Playing: mediacontrol. isplaying = true; tbmessage. Text =" playing. "; Btnplayorpause. content = "paused"; break; Case mediaelementstate. stopped: mediacontrol. isplaying = false; tbmessage. TEXT = "STOPPED"; btnplayorpause. content = "play"; break; default: break;} private void mymediaelement_mediafailed_1 (Object sender, exceptionroutedeventargs e) {tbmessage. TEXT = "An error occurred while playing the audio. Please check your character. ";} Private void mymediaelement_mediaended_1 (Object sender, routedeventargs e) {// after playing the video, unbind the event to mediacontrol. playpressed-= mediacontrol_playpressed; mediacontrol. playpausetogglepressed-= mediacontrol_playpausetogglepressed; mediacontrol. pausepressed-= mediacontrol_pausepressed; mediacontrol. stoppressed-= mediacontrol_stoppressed;} private void mymediaelement_mediaopened_1 (Object sender, ROU Tedeventargs e) {// registers a playback control event mediacontrol. playpressed + = mediacontrol_playpressed; mediacontrol. playpausetogglepressed + = mediacontrol_playpausetogglepressed; mediacontrol. pausepressed + = mediacontrol_pausepressed; mediacontrol. stoppressed + = mediacontrol_stoppressed; // display the title of the song and the name of the singer mediacontrol. trackname = This. musictitle; mediacontrol. artistname = This. musicartist;} async void mediacontrol_sto Ppressed (Object sender, Object E) {await dispatcher. runasync (windows. UI. core. coredispatcherpriority. normal, () => {This. mymediaelement. stop () ;}) ;} async void mediacontrol_pausepressed (Object sender, Object E) {await dispatcher. runasync (windows. UI. core. coredispatcherpriority. normal, () => {This. mymediaelement. pause () ;});} async void mediacontrol_playpausetogglepressed (Object sender, Object E) {await dispatcher. runasync (windows. UI. core. coredispatcherpriority. normal, () =>{ onplayorpause (null, null) ;});} async void mediacontrol_playpressed (Object sender, Object E) {await dispatcher. runasync (windows. UI. core. coredispatcherpriority. normal, () => {This. mymediaelement. play () ;}) ;}private async void onselectfile (Object sender, routedeventargs e) {fileopenpicker picker = new fileope Npicker (); picker. filetypefilter. add (". MP3 "); picker. filetypefilter. add (". WMA "); picker. suggestedstartlocation = pickerlocationid. musiclibrary; storagefile audiofile = await picker. picksinglefileasync (); If (audiofile! = NULL) {// obtain the audio file property var musickproperty = await audiofile. properties. getmusicpropertiesasync (); this. musictitle = musickproperty. Title; If (! String. isnullorempty (musickproperty. albumartist) {This. musicartist = musickproperty. albumartist;} else {This. musicartist = musickproperty. artist;} // sets the playback source var stream = await audiofile. openasync (fileaccessmode. read); this. mymediaelement. setsource (stream, audiofile. filetype) ;}} private void onplayorpause (Object sender, routedeventargs e) {If (this. mymediaelement. currentstate = mediaelementstate. playing) {This. mymediaelement. pause ();} else {This. mymediaelement. play () ;}} private void onstop (Object sender, routedeventargs e) {This. mymediaelement. stop ();}}}

The code will be summarized later. Now we can't wait to see if the experiment is successful. Run it decisively.

Select an MP3 file on your computer, click play, and switch to the Start Screen to see if the music continues playing? If yes, the experiment is successful.

 

If your laptop keyboard has a multimedia control key, on the task screen, press the volume control key, you will see the control button as shown on the screen.

 

Okay, this is the general background playback situation.

In this example, if you set the audiocategory attribute of mediaelement to backgroundcapablemedia without registering mediacontrol event processing, you will find that, it cannot be played in the background.

The mediacontrol class is located in the windows. Media namespace. This class is indispensable for playing and controlling audio in the background. It is a static class, so you can think of all its members as static. It has n multiple events, as shown below. You may wish to open "Object Browser" and study it.

 

In this experiment, we registered only four events, which are also the most basic four. You can try it and comment out one of them, so it cannot be played in the background, these four events are required, and others are optional.

A better solution is to register these events in the loaded event on the page with mediaelement and release them in unloaded. However, this example is different. This example is registered when the media is turned on and released when the media is turned off, because only one audio is played in this example. So there is no "first" or "Next ".

 

 

 

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.