Reputation: 47
I've searched a lot, through msdn site, stackoverflow etc.. but i can't make playing a song in background. It stops when change frame, or exiting from the app returning to start, it also starts randomly when it is on lockscreen or in another places.. Can you explain how correctly do this code please? Sorry for bad code but i've started few days ago.
this is more or less what i found on microsoft site. There are also no system it doesn't show any control
public sealed partial class listView : Page
{
SystemMediaTransportControls Player = SystemMediaTransportControls.GetForCurrentView();
SystemMediaTransportControls systemControls;
MediaElement musicPlayer = new MediaElement();
public listView()
{
this.InitializeComponent();
makeSongList();
// Per usare il tasto back
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
// Hook up app to system transport controls.
systemControls = SystemMediaTransportControls.GetForCurrentView();
systemControls.ButtonPressed += SystemControls_ButtonPressed;
// Register to handle the following system transpot control buttons.
systemControls.IsEnabled = true;
systemControls.IsPlayEnabled = true;
systemControls.IsPauseEnabled = true;
systemControls.IsNextEnabled = true;
systemControls.IsPreviousEnabled = true;
musicPlayer.AudioCategory = AudioCategory.BackgroundCapableMedia;
}
void MusicPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
{
// gestisce l'evento CurrentStateChanged di MediaElement e
// aggiorna la proprietà PlaybackStatus di SystemMediaTransportControls.
switch (musicPlayer.CurrentState)
{
case MediaElementState.Playing:
systemControls.PlaybackStatus = MediaPlaybackStatus.Playing;
break;
case MediaElementState.Paused:
systemControls.PlaybackStatus = MediaPlaybackStatus.Paused;
break;
case MediaElementState.Stopped:
systemControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
break;
case MediaElementState.Closed:
systemControls.PlaybackStatus = MediaPlaybackStatus.Closed;
break;
default:
break;
}
}
async private void UpdateSongInfo()
{
// Get the updater.
SystemMediaTransportControlsDisplayUpdater updater = systemControls.DisplayUpdater;
// Get the music file and pass it to CopyFromFileAsync to extract the metadata
// and thumbnail. StorageFile is defined in Windows.Storage
StorageFile musicFile =
await StorageFile.GetFileFromApplicationUriAsync(new Uri(currentPath));
await updater.CopyFromFileAsync(MediaPlaybackType.Music, musicFile);
// Update the system media transport controls
updater.Update();
}
void MusicPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
UpdateSongInfo();
}
void SystemControls_ButtonPressed(SystemMediaTransportControls sender,
SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Play:
PlayMedia();
break;
case SystemMediaTransportControlsButton.Pause:
PauseMedia();
break;
default:
break;
}
}
async void PlayMedia()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
musicPlayer.Play();
});
}
async void PauseMedia()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
musicPlayer.Pause();
});
}
Upvotes: 0
Views: 1488
Reputation: 47
SOLVED WITH THIS!!!!
http://mark.mymonster.nl/2014/05
I was stuck and I read thousand of pages but that sample it's really simple and clear!
The main problem was to create a windows Runtime component and follow the typical implementation of the Run istance for backgroundMediaPlayer with its handlers.
using System;
using System.Diagnostics;
using Windows.ApplicationModel.Background;
using Windows.Foundation.Collections;
using Windows.Media;
using Windows.Media.Playback;
namespace PLAYER
{
public sealed class BackgroundTask : IBackgroundTask
{
private string Artista { get; set; }
private string Titolo { get; set; }
private BackgroundTaskDeferral _deferral;
private SystemMediaTransportControls _systemMediaTransportControl;
public void Run(IBackgroundTaskInstance taskInstance)
{
_systemMediaTransportControl = SystemMediaTransportControls.GetForCurrentView();
_systemMediaTransportControl.IsEnabled = true;
BackgroundMediaPlayer.MessageReceivedFromForeground += MessageReceivedFromForeground;
BackgroundMediaPlayer.Current.CurrentStateChanged += BackgroundMediaPlayerCurrentStateChanged;
// Associate a cancellation and completed handlers with the background task.
taskInstance.Canceled += OnCanceled;
taskInstance.Task.Completed += Taskcompleted;
_deferral = taskInstance.GetDeferral();
}
private void MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
{
ValueSet valueSet = e.Data;
foreach (string key in valueSet.Keys)
{
switch (key)
{
case "Title":
Titolo = valueSet[key].ToString();
break;
case "Artist":
Artista = valueSet[key].ToString();
break;
case "Play":
Debug.WriteLine("Starting Playback");
Play(valueSet[key].ToString());
break;
}
}
}
private void Play(string toPlay)
{
MediaPlayer mediaPlayer = BackgroundMediaPlayer.Current;
mediaPlayer.AutoPlay = true;
mediaPlayer.SetUriSource(new Uri(toPlay));
_systemMediaTransportControl.ButtonPressed += MediaTransportControlButtonPressed;
_systemMediaTransportControl.IsPauseEnabled = true;
_systemMediaTransportControl.IsPlayEnabled = true;
_systemMediaTransportControl.IsNextEnabled = true;
_systemMediaTransportControl.IsPreviousEnabled = true;
_systemMediaTransportControl.DisplayUpdater.Type = MediaPlaybackType.Music;
_systemMediaTransportControl.DisplayUpdater.MusicProperties.Artist = Artista;
_systemMediaTransportControl.DisplayUpdater.MusicProperties.Title = Titolo;
_systemMediaTransportControl.DisplayUpdater.Update();
}
/// <summary>
/// The MediaPlayer's state changes, update the Universal Volume Control to reflect the correct state.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void BackgroundMediaPlayerCurrentStateChanged(MediaPlayer sender, object args)
{
if (sender.CurrentState == MediaPlayerState.Playing)
{
_systemMediaTransportControl.PlaybackStatus = MediaPlaybackStatus.Playing;
}
else if (sender.CurrentState == MediaPlayerState.Paused)
{
_systemMediaTransportControl.PlaybackStatus = MediaPlaybackStatus.Paused;
}
}
/// <summary>
/// Handle the buttons on the Universal Volume Control
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void MediaTransportControlButtonPressed(SystemMediaTransportControls sender,
SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Play:
BackgroundMediaPlayer.Current.Play();
break;
case SystemMediaTransportControlsButton.Pause:
BackgroundMediaPlayer.Current.Pause();
break;
}
}
private void Taskcompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
BackgroundMediaPlayer.Shutdown();
_deferral.Complete();
}
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
// You get some time here to save your state before process and resources are reclaimed
BackgroundMediaPlayer.Shutdown();
_deferral.Complete();
}
}
}
Upvotes: 1
Reputation: 3304
You are using SystemMediaTransportControls, so it should be a windows runtime app for windows phone 8.1.
Actually, you missed many things that can help you to implement the background audio. For example: You did not try to get a BackgroundTaskDeferral to keep the background task active, and you also did not use BackgroundMediaPlayer to communicate with the global media player for manipulating audio playback.
So I will suggest first go through the Overview: Background audio (Windows Phone Store apps) article and check how the offcial sample (you can mainly focus on MyBackgroundAudioTask.cs in SampleBackgroundAudioTask project) implements.
Upvotes: 1