I have UWP(Universal Windows Platform) Application and I want to add shoutcast player, but can't find anything how to do that.
I have Button which should start/stop playing music and volume slider.
I found element in xaml such as MediaElement but when I'm trying to use it like that:
private async void StartPlayer()
{
var result = await AdaptiveMediaSource.CreateFromUriAsync(new Uri("http://camon22.sxcore.net:"+Port, UriKind.Absolute));
if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
{
var astream = result.MediaSource;
Media.SetMediaStreamSource(astream);
}
else
{
var dialog = new MessageDialog("Result Status Wrong!\n"+result.Status);
await dialog.ShowAsync();
}
}
I got UnsupportedManifestContestType Status.
Anybody knows how to play radio in UWP application?
Related
So I was trying to loop Background music in my UWP App, I have a class called soundControl that handles music and sounds like this:
public class soundControl
{
private static MediaElement loop = new MediaElement();
public static async void stopLoop()
{
loop.Stop();
}
public static async void loadLoopTimeBG()
{
Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(#"Assets\Sounds");
Windows.Storage.StorageFile file = await folder.GetFileAsync("battle.wav");
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
loop.AutoPlay = false;
loop.SetSource(stream, file.ContentType);
loop.IsLooping = true;
}
public static void loopTimeBG()
{
loop.Play();
}
And whenever I want to play this music I call :
soundControl.loadLoopTimeBG();
soundControl.loopTimeBG();
the problem is the it plays just one time and stops and I have no Idea why
I tried another approach like:
loop.MediaEnded += mediaEnded;
and the event handler like this:
private static void mediaEnded(object sender, RoutedEventArgs e)
{
loop.Position = TimeSpan.Zero;
loop.Play();
}
it also didn't work and when debugging it doesn't even triger the mediaEnded event when music is complete.
Any help here would be most appreciated.
Thanks
MediaPlayer
Windows.Media.Playback.MediaPlayer is the recommended player for UWP that does not require to be in the XAML visual tree.
Its API is very similar to MediaElement:
private static MediaPlayer _mediaPlayer = new MediaPlayer();
public static async Task PlayUsingMediaPlayerAsync()
{
Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(#"Assets");
Windows.Storage.StorageFile file = await folder.GetFileAsync("Click.wav");
_mediaPlayer.AutoPlay = false;
_mediaPlayer.Source = MediaSource.CreateFromStorageFile(file);
_mediaPlayer.MediaOpened += _mediaPlayer_MediaOpened;
_mediaPlayer.IsLoopingEnabled = true;
}
private static void _mediaPlayer_MediaOpened(MediaPlayer sender, object args)
{
sender.Play();
}
You can even display the visuals of a MediaPlayer in XAML using MediaPlayerElement.
MediaPlayer allows for even more advanced playback scenarios using the MediaPlaybackList with support for looping, shuffle and gapless playback.
mediaElement.SetPlaybackSource(mediaPlaybackList);
MediaElement
After some digging around it seems that there are two issues.
MediaElement is XAML based control (in the Windows.UI.Xaml.Controls namespace), and it seems that it does not work properly until it is actually attached to a visual tree. Once you put the MediaElement on the page, it works as expected.
Secondly, loading source media does not happen immediately. Once you set the source, the control needs some time to actually load the media. For this purpose, you can use the MediaOpened event, that will notify you once it is really loaded.
So the code could look somewhat like this:
public static async Task LoadAndPlayAsync()
{
Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(#"Assets");
Windows.Storage.StorageFile file = await folder.GetFileAsync("Click.wav");
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
loop.AutoPlay = false;
loop.SetSource(stream, file.ContentType);
//or simpler -
//loop.Source = new Uri("ms-appx:///Assets/Click.wav", UriKind.Absolute);
loop.MediaOpened += Loop_MediaOpened;
loop.IsLooping = true;
}
private static void Loop_MediaOpened(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
//play once the media is actually ready
loop.Play();
}
And before you call the LoadAndPlayAsync method, you have to attach the control somewhere (for example in a Grid):
GridContainer.Children.Add(SoundController.loop);
await SoundController.LoadAndPlayAsync();
I have created a sample project for my tests on my GitHub, you can check it out to see how I implemented it. The first button in the app attaches the control and the second loads and plays the sound. You can see that if you click only the second one, the sound does not play.
I am making a UWP App where I run Background Audio in the MainPage on a Button Click event. When I move to another page, there's also a different Media to play in Background Audio Task there.
How can I stop the currently playing Task to run the other? Should I define something globally? Any help regarding this issue?
Edit
I am using this sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BackgroundAudio While the backgroundAudio of the first Page is running, I go to the second page and on a click event I set a new List with the following code:
// First update the persisted start track
ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, RadioFacade.mySongs[0].MediaUri.ToString()); //here
ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.Position, new TimeSpan().ToString());
// Start task
StartBackgroundAudioTask();
But the new song takes more than the estimated time to run and enter the else of this method:
private void StartBackgroundAudioTask()
{
AddMediaPlayerEventHandlers();
var startResult = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
bool result = backgroundAudioTaskStarted.WaitOne(10000);
//Send message to initiate playback
if (result == true)
{
MessageService.SendMessageToBackground(new UpdatePlaylistMessage(RadioFacade.mySongs));
MessageService.SendMessageToBackground(new StartPlaybackMessage());
}
else
{
throw new Exception("Background Audio Task didn't start in expected time");
}
});
startResult.Completed = new AsyncActionCompletedHandler(BackgroundTaskInitializationCompleted);
}
and the old (first playing) song keeps playing.
I tried to Stop the current BackgroundMediaPlayer using BackgroundMediaPLayer.Shutdown() but it didn't work.
Any idea how to let the old song stop and the current song play?
You can control the background media player by sending messages to it from the foreground. For example,
From the foreground app:
BackgroundMediaPlayer.SendMessageToBackground(new ValueSet
{
{"playnew", "some value"}
});
In your background task:
public sealed class AudioPlayer : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
...
...
}
private async void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
{
object value;
if (e.Data.TryGetValue("playnew", out value) && value != null)
{
// value will be whatever you pass from the foreground.
BackgroundMediaPlayer.Current.Pause();
BackgroundMediaPlayer.Current.Source = stream source;
BackgroundMediaPlayer.Current.Play();
}
}
...
}
"playnew" can be a global constant in your application. You can use the ValueSet to pass the live stream url to the background task as the value.
In my application I want to notify the user with the ShellToast.
Just by running...
var toast = new ShellToast
{
Title = "Nom nom nom!",
Content = "More! More! Keep feeding me!",
};
toast.Show();
...makes nothing happen, and as I understand it needs to be run from a ScheduledTaskAgent. But how do I run this on command, and make sure it only run once?
You can't use a ShellToast while the app is the foreground app. It's meant to be invoked from a background service while the app isn't the foreground app.
If you want to have a UX similar to that of ShellToast use the Coding4fun toolkit ToastPrompt control. Here's a code snippet showing how to use it:
private void ToastWrapWithImgAndTitleClick(object sender, RoutedEventArgs e)
{
var toast = GetToastWithImgAndTitle();
toast.TextWrapping = TextWrapping.Wrap;
toast.Show();
}
private static ToastPrompt GetToastWithImgAndTitle()
{
return new ToastPrompt
{
Title = "With Image",
TextOrientation = System.Windows.Controls.Orientation.Vertical,
Message = LongText,
ImageSource = new BitmapImage(new Uri("../../ApplicationIcon.png", UriKind.RelativeOrAbsolute))
};
}
Running this code snippet shows the following:
Just a small update: using ShellToast when the app is in foreground, is now possible, when using Windows Phone 8 Update 3. Though, they are obscured by other activity such as a phone call or the lock screen. Source
In my application I want to notify the user with the ShellToast.
Just by running...
var toast = new ShellToast
{
Title = "Nom nom nom!",
Content = "More! More! Keep feeding me!",
};
toast.Show();
...makes nothing happen, and as I understand it needs to be run from a ScheduledTaskAgent. But how do I run this on command, and make sure it only run once?
You can't use a ShellToast while the app is the foreground app. It's meant to be invoked from a background service while the app isn't the foreground app.
If you want to have a UX similar to that of ShellToast use the Coding4fun toolkit ToastPrompt control. Here's a code snippet showing how to use it:
private void ToastWrapWithImgAndTitleClick(object sender, RoutedEventArgs e)
{
var toast = GetToastWithImgAndTitle();
toast.TextWrapping = TextWrapping.Wrap;
toast.Show();
}
private static ToastPrompt GetToastWithImgAndTitle()
{
return new ToastPrompt
{
Title = "With Image",
TextOrientation = System.Windows.Controls.Orientation.Vertical,
Message = LongText,
ImageSource = new BitmapImage(new Uri("../../ApplicationIcon.png", UriKind.RelativeOrAbsolute))
};
}
Running this code snippet shows the following:
Just a small update: using ShellToast when the app is in foreground, is now possible, when using Windows Phone 8 Update 3. Though, they are obscured by other activity such as a phone call or the lock screen. Source
In my WP7 gaming app , I want two music files to run. One is the background music and another follows the user action , say, user kills the enemy. I am using MediaElement to do this. I am facing two issues.
1) How to loop background music ?
2) As soon as second music starts, the first music stops and does not start back when the second music stops. I do not want background music to stop, they should overlap. How to do this ?
I am using silverlight.
XAML
<MediaElement x:Name="stroke" AutoPlay="False" />
<MediaElement x:Name="bmusic" AutoPlay="True" />
C#
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("bm"))
{
string hy=(string)settings["bm"];
//check if user has disabled music play
if (hy == "1")
{
bmplay = 1;
// play background music
bmusic.Source = new Uri("bmusic.mp3", UriKind.Relative);
bmusic.Play();
}
else
{
bmplay = 0;
}
}
else
{
bmplay = 1;
// play b music
bmusic.Source = new Uri("bmusic.mp3", UriKind.Relative);
bmusic.Play();
}
if (NavigationContext.QueryString.TryGetValue("msg", out msg))
{
// textBox1.Text +=" "+ msg;
find_move();
}
}
For repeating music you can use this:
Song s = Song.FromUri("song", new Uri(path));
FrameworkDispatcher.Update();
MediaPlayer.IsRepeating = repeat;
MediaPlayer.Play(s);
And try to use SoundEffect for sounds, they can be played simultaneously with background music.
Sound effect in windows phone 7