Search code examples
c#windows-phonewindows-phone-8.1

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!


Solution

  • 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.