简体   繁体   中英

Play sound in windows phone 8.1 background

I am writing an app which require background music. Below is my code which i made after searching different forums.

class AudioPlayer : IBackgroundTask
{
    private BackgroundTaskDeferral _deferral;
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        _deferral = taskInstance.GetDeferral();
        taskInstance.Canceled += TaskInstance_Canceled;
    }
    private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
    {
        _deferral.Complete();
    }

    //===========================================================================================================
    public void startTick()
    {
        BackgroundMediaPlayer.Current.SetUriSource(new Uri("ms-appx:///Audio/clock.wav"));
        BackgroundMediaPlayer.Current.Play();
    }
}  

Problem is it doesnt work. No sound from emulator. Please Help!

There are few things that might have gone wrong (I guess it's not all your code). The best would be here if you would follow Bacground Audio Overview .

Please also check if you had added needed declarations (I suspect that this may be a problem here): go to your Package.appxmanifest file, open Declarations then you should add Background Tasks with an Audio (as suppoerted task type) and specify its entry point (probably yournamespace.AudioPlayer ).

Also remember that, as said at MSDN (the link above):

Your background task starts the first time your app accesses BackgroundMediaPlayer.Current in foreground app code.

I advise to set a breakpoint at Run method and you should see if AudioPlayer had started. Also remember to provide communication between UI and AudioPalyer - ToUI and ToPlayer (of course if you need it).

You may also want to configure your SMTP , so that your AudioPlayer would react to those buttons that show when you hit VolumeControl.

为了帮助您理解BackgroundMediaPlayer的正确用法,请看一下示例,您的想法将变得清晰。您必须集成另一个项目的引用以使用背景Audio。只需看一下即可。希望对您有所帮助。

In case someone else stumbles across this, any IBackgroundTask on Win Phone 8.1 needs to be contained in a WinRT component project type and not in a class library or PCL.

The MediaPlayer exe will just exit and you'll be left pulling out your hair if you give it a dll.

That and make sure you entry point path is correct in your appxmanifest file and you should be good to go. Just put a breakpoint in your Run() method to verify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM