"WP Dev" plays sound when the phone screen is lit.

Source: Internet
Author: User

Today's content is a bit of a rogue, please gentlemen in the development of applications with caution.

So, how many hooligans is this job?

Let's start by introducing the features you want to do: play short music when the user presses the Power key (or double-tap the screen) to light the phone's screen, and the application can play when it's not running in the foreground .

A friend in mind may immediately emerge with two words: background audio, background tasks .

Yes, Gray is always correct and can play sound when the application is not running in the foreground or running, only with background audio. Well, that's the way it works, I'm sure there's nothing hard to understand. Here's how to achieve this.

Playing back audio in 8.1 can be done using the Backgroundmediaplayer class under the Windows.Media.Playback namespace, which is designed to operate audio playback between the foreground and the background, both in the foreground and in the background. By using the static Current property, you can return a MediaPlayer instance, which is compared to the MediaElement in XAML, but MediaPlayer is dedicated to play the sound and cannot see the film.

So we will think that the first step is to set the source for MediaPlayer, there are three ways to set the playback source.

1, Setfilesource method, directly to a music file Storagefile instance can be passed in;

2. The SetStreamSource method is transmitted in the form of a stream;

3, Seturisource method, directly to the URI to set the source.

Of course, there is a Setmediasource method, this thing is more complicated, temporarily do not consider.

If the MediaPlayer AutoPlay is set to true, it plays immediately after the source is set and if false, it will need to call the play method before it plays.

Now, we have to consider the most "headache" problem, how to run a background task when the phone screen is lit? Don't worry, come on, look slowly.

The Windows.ApplicationModel.Background namespace defines a number of background task triggers that trigger a background task, with a trigger class specifically designed to capture the--systemtrigger of system events. When you create an Systemtrigger instance, you specify Systemtriggertype, which represents the trigger behavior type, defined by the Systemtriggertype enumeration. Let's take a look at two of these values:

Userpresent: What does it mean to trigger the background when the user is visible? On a tablet or computer, it is triggered when the user logs on to the system, while on the phone it is triggered when the user presses the power key to light the phone screen. Haha, now do you know how to play the sound when the screen is lit?

Useraway: Triggered when the user logs off on a computer or tablet, and on the phone when the user shuts down the screen, so you can use this type if you want the sound to play on the lock screen.

Now, you must understand the idea. is implemented with background audio and triggers. However, please seriously remember, in the light of the screen when the sound is not too long, you do not come to a song, that would be very disgusting and rogue, and the system will not let you play so long, so, not too rogue. Therefore, it is advisable to use about 5 seconds of sound.

Okay, what are you doing?

First add a run-time component project in the solution, note that it is not a class library, it is a runtime component, and a. WIMD suffix is generated after compilation, not a. dll, and the class library is the. dll.

This runtime component is to perform the background task, define a class, and implement the Ibackgroundtask interface, to implement this interface, the system will recognize you as a post-task, otherwise the system does not bird you.

     Public Sealed classBack:ibackgroundtask {backgroundtaskdeferral Deferral=NULL;  Public Async voidRun (ibackgroundtaskinstance taskinstance) {Deferral=taskinstance.getdeferral (); Uri Media=NewUri ("Ms-appx:///1.mp3"); //Open File StreamStorageFile file =awaitstoragefile.getfilefromapplicationuriasync (media); varstream =awaitfile.            OpenReadAsync (); //get the Player control objectMediaPlayer player =backgroundmediaplayer.current; Player. AutoPlay=true;//Set auto PlayPlayer. mediaended + =player_mediaended; Player. MediaFailed+=player_mediafailed; //Auto play after setting sourceplayer.        SetStreamSource (stream); }        voidplayer_mediafailed (MediaPlayer sender, Mediaplayerfailedeventargs args) {Backgroundmediaplayer.            Shutdown ();        Deferral.complete (); }        voidPlayer_mediaended (MediaPlayer sender,Objectargs)            {Backgroundmediaplayer.shutdown ();        Deferral.complete (); }    }

The code is not very long, should be able to understand, is to get the player from the Backgroundmediaplayer.current, after the player has given it setsource,set after the source has started to play the sound.
So what is the use of the Backgroundtaskdeferral object returned by the Getdeferral method? Plainly, is used to delay the time, do not let the background task so quickly end, and so on after the sound playback end, listen to the fairy music after the death is not too late. When you feel like, to end the background task, call the complete method to tell the system, this background task is finished, the buried, so the system will x off the background and recycling resources.

Good, the background task is written, and then the front desk,

The first thing to do in the foreground application is to refer to the runtime component just written, just like the reference assembly, right-click on the "Reference", and then "Add Reference", I believe you will do it, otherwise you are not learning. Net.

Then open the manifest file package.appxmanifest, switch to the "Declarations" tab, select "Background Tasks" in the drop-down list, then click the Add button, OK, the background declaration added. Then you set the parameters.

Check "audio" under supported task types, note that only audio is available, do not select other, or you will not be able to run the program. Such as.

Next, at the entry point, fill in the class name of the implementation Ibackgroundtask interface that was written in the runtime component, and note that the namespace name is also filled in, such as.

OK, save and close the manifest file, but the background task is not registered yet, the statement just tells the system which background tasks are allowed, and does not actually register.

can be registered in the Onnavigated method of the page, you can also register in the app's Onlaunch method, as you like, anyway to register before the background task runs.

            foreach(ibackgroundtaskregistration TaskinchBackgroundTaskRegistration.AllTasks.Values) {if(Task. Name = =taskname) {Task.} Unregister (true);  Break; }            }            //You must call the following code, or you cannot register a background task            varresult =awaitBackgroundexecutionmanager.requestaccessasync (); if(Result = =backgroundaccessstatus.allowedmayuseactiverealtimeconnectivity) {Backgroundtaskbuilder tas KBD=NewBackgroundtaskbuilder (); TASKBD. Name=TaskName; TASKBD. Taskentrypoint= Entry_point;//entry point//Add TriggerSystemtrigger trigger =NewSystemtrigger (Systemtriggertype.userpresent,false); /** Triggers when the user lights up the phone screen.*/TASKBD.                Settrigger (trigger); //registering a background task                Try                {                    varReg =TASKBD.                    Register (); Tb. Text="Background Task registration succeeded. \ n"+string. Format ("Task Name: {0}\n"Reg. Name) +string. Format ("Task id:{0}", Reg.                TASKID); }                Catch{TB. Text="Background Task registration failed. "; }            }

First from the BackgroundTaskRegistration.AllTasks.Values to find out whether the task is already registered, if it is, first kill it, and then re-register.

Because you want to play a sound when the user lights up the phone screen, the Systemtrigger trigger uses a type of userpresent.

There is also a critical place, before registering a background task, Do not forget to call the Backgroundexecutionmanager.requestaccessasync method, although you do not see the prompt after the call, but you must call the method and return Backgroundaccessstatus.allowedmayuseactivere Altimeconnectivity before you can register a background task, or an error occurs.

Okay, that's it. Run the application, let it register the background task, and then you can turn off the program. Then turn off the phone screen and then light the screen, you can hear the fairy music.

Sample source code Download: Http://files.cnblogs.com/tcjiaan/playAudioOnPresentSP.zip

"WP Dev" plays sound when the phone screen is lit.

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.