How to play background music online in Windows 8 - c#

In my application, I use UI MediaElement. But when i click the Windows key, the music stops.
I tried using:
MediaControl.PlayPressed += MediaControl_PlayPressed;
MediaControl.PausePressed += MediaControl_PausePressed;
MediaControl.PlayPauseTogglePressed += MediaControl_PlayPauseTogglePressed;
MediaControl.StopPressed += MediaControl_StopPressed;
I set source MediaElement:
media.Source = new Uri("http://stream-hq.mp3.zdn.vn/fsgggsfdlwjglwjAAAAA/2a3f830202ea6d29bc7c5a5146401566/4ff5620a/2011/12/27/a/4/a4fcc199a184a93cfeb0fe35642c53bf.mp3", UriKind.RelativeOrAbsolute);
Please help me!

For a Metro/WinRT app to play audio in background, the app needs the following:
A MediaElement control that:
Is in a XAML page.
The AudioCategory property set to BackgroundCapableMedia (as in Armando's answer). There are other values for games or communication systems as needed. See the Audio Playback in a Metro Application for information on what the different options mean.
Use the MediaControl object to capture at least the following. Other events and properties can be handled if desired but the following are required for background playback to function.
PlayPressed
StopPressed
PlayPauseTogglePressed
PausePressed
Add audio to the list of support background tasks in the applications manifest. The manifest is usually called Package.appxmanifest. Select it in the Solution Explorer, go to the Declarations tab and check "Audio" as shown:
See the Transport Controls Guide for more info about capturing hardware buttons (e.g. play/pause on the keyboard) and the quickstart guide for creating a media player for more info.

This would be my first answer. Make sure you set AudioCategory="BackgroundCapableMedia" in your XAML like this:
<MediaElement x:Name="backgroundMusic"
AutoPlay="True"
AudioCategory="BackgroundCapableMedia"
Source="mms://betafm.santafe-conicet.gov.ar:1175">
</MediaElement>
Hope it helps!

Related

What WP 8.1 XAML control could look and behave like the system Task switcher?

I'm writing a Windows Phone 8.1 Store app and I need to create a control so that it looks and behaves similar to WP 8.1 system task switcher (that appears when holding back hardware button).
It should show some images and support sliding left or right when swiping. Does anyone know what control should I use or do I need to create a completely new control from scratch?
So, the sollution was easy. The control I was looking for was... a ScrollViewer. It has 2 properties in WinRT XAML that make the ScrollViewer scrolling behave like I wanted: HorizontalSnapPointsAlignment and HorizontalSnapPointsType.
If you want to try this behavior, this MSDN code sample will expose it for you.
One point to mention. If you wish to set such behavior to, for example, a ListView you should firstly get its internal ScrollViewer in code and then set its HorizontalSnapPointsAlignment and HorizontalSnapPointsType properties. You can use GetFirstDescendantOfType<T>() extension method from WinRT XAML toolkit.
var sv = myListView.GetFirstDescendantOfType<ScrollViewer>();
sv.HorizontalSnapPointsAlignment = SnapPointsAlignment.Center;
sv.HorizontalSnapPointsType = SnapPointsType.Mandatory;

WinRT MediaElement: Detect changes from fullscreen to normal when IsFullWindow is true and AreTransportControlsEnabled is true

Context: WinRT, Universal Apps, XAML, C#
I am creating a video player application in which one of the requirements is that the video plays exclusively in fullscreen, and when the video returns from fullscreen, the video should be stopped and the user should be taken to a summary page. Currently I am using MediaElement.IsFullWindow and MediaElement.AreTransportControlsEnabled in order to play the video in fullscreen and it works perfectly well, when the video ends I grab the MediaEnded event and take the user back to the summary page, setting IsFullWindow to false and AreTransportControlsEnabled to false.
The only problem is that Transport Controls have a fullscreen button that takes the user back to the non-fullscreen layout and the video keeps on playing.
On most applications this would be great, but on this one, I need to stop the video when it happens.
Unfortunately, when this happens, IsFullWindow is not set to false, the SizeChanged event for the MediaElement is not fired and there seems to be no other notification that the user has decided to leave fullscreen mode.
So I am trapped in a situation in which I am unable to find out whether the video is truly playing in fullscreen or not.
If I pause the video and the user plays it again, since IsFullWindow is true, it will go back to fullscreen and if I let the video play to the end everything works fine and the user goes to the summary page.
Does anybody have any suggestions on how I may be able to detect this change in order to stop the video?
An alternative solution is not to use transport control provided by media element and create your own custom media controls .
See this MSDN link which explains how to create custom media transport controls
When changed IsFullWindow status fires SizeChanged of Window.Current instead of MediaElement. You just should attach to this event
Window.Current.SizeChanged += this.OnWindowSizeChanged;
and check IsFullWindow of MediaElement when it fired.
private void OnWindowSizeChanged(object sender, WindowSizeChangedEventArgs windowSizeChangedEventArgs)
{
if (!this.mediaElement.IsFullWindow)
{
}
else
{
}
}
I ended up using the Microsoft Player Framework which gives me events and properties to control all I needed without having to write my own code and incur in design work for the video player control assets.
You can overcome this issue by binding, IFullWindow MediaElement property with "TwoWay" mode, and act accordingly to its value on set :)
You may use a DispatcherTimer called every 100 ms, check the status of the IsFullWindow property, and if property value changes, fire an event or call your own function.

Disable next/prev buttons in Universal Volume Control (uvc) when using AudioPlayerAgent

I'm currently working on an radio app for WP7 Mango and I want to disable the next and the previous track buttons in the UVC like last.fm did in their app, but I can't figure out how.
Can someone help me with this?
You can select which controls are active in the UVC when you create the track to play in your agent (i.e. from the code which handles the TrackEnded event in the Background Audio Agent).
For example:
EnabledPlayerControls controls = EnabledPlayerControls.Pause |
EnabledPlayerControls.Rewind |
EnabledPlayerControls.FastForward;
AudioTrack track = new AudioTrack(
trackUri,
trackTitle,
trackBy,
trackAlbum,
trackAlbumArtUri,
trackTag,
controls);
...
return track
This will allow you to be able to make the agent skip tracks when your application wants, but Skip won't work by tapping the buttons on the UVC.
(In this example if the user taps and holds the fast-forward and rewind buttons in the UVC, the track will still fast-forward/rewind).
If you don't supply a entire playlist, but only a single MediaHistory , the Previous/Next buttons should be automatically disabled.
The same should apply to the AudioStreamingAgent. If you wish to disable the ability to use the buttons, handle the BackgroundAudioPlayer.Instance.PlayStateChanged event, see WP7 Mango: How to handle skip next/previous from UVC outside of the Audio Playback Agent class library? for details.
Post some code, if you want more detailed help.

How to play a sound in C#, .NET

I have a Windows application written in C#/.NET.
How can I play a specific sound when a button is clicked?
You could use:
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"c:\mywavfile.wav");
player.Play();
You can use SystemSound, for example, System.Media.SystemSounds.Asterisk.Play();.
For Windows Forms one way is to use the SoundPlayer
private void Button_Click(object sender, EventArgs e)
{
using (var soundPlayer = new SoundPlayer(#"c:\Windows\Media\chimes.wav")) {
soundPlayer.Play(); // can also use soundPlayer.PlaySync()
}
}
MSDN page
This will also work with WPF, but you have other options like using MediaPlayer MSDN page
Additional Information.
This is a bit high-level answer for applications which want to seamlessly fit into the Windows environment. Technical details of playing particular sound were provided in other answers. Besides that, always note these two points:
Use five standard system sounds in typical scenarios, i.e.
Asterisk - play when you want to highlight current event
Question - play with questions (system message box window plays this one)
Exclamation - play with excalamation icon (system message box window plays this one)
Beep (default system sound)
Critical stop ("Hand") - play with error (system message box window plays this one)
 
Methods of class System.Media.SystemSounds will play them for you.
 
Implement any other sounds as customizable by your users in Sound control panel
This way users can easily change or remove sounds from your application and you do not need to write any user interface for this – it is already there
Each user profile can override these sounds in own way
How-to:
Create sound profile of your application in the Windows Registry (Hint: no need of programming, just add the keys into installer of your application.)
In your application, read sound file path or DLL resource from your registry keys and play it. (How to play sounds you can see in other answers.)
Code bellow allows to play mp3-files and in-memory wave-files too
player.FileName = "123.mp3";
player.Play();
from http://alvas.net/alvas.audio,samples.aspx#sample6 or
Player pl = new Player();
byte[] arr = File.ReadAllBytes(#"in.wav");
pl.Play(arr);
from http://alvas.net/alvas.audio,samples.aspx#sample7
To play an Audio file in the Windows form using C# let's check simple example as follows :
1.Go Visual Studio(VS-2008/2010/2012) --> File Menu --> click New Project.
2.In the New Project --> click Windows Forms Application --> Give Name and then click OK.
A new "Windows Forms" project will opens.
3.Drag-and-Drop a Button control from the Toolbox to the Windows Form.
4.Double-click the button to create automatically the default Click event handler, and add the following code.
This code displays the File Open dialog box and passes the results to a method named "playSound" that you will create in the next step.
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Audio Files (.wav)|*.wav";
if(dialog.ShowDialog() == DialogResult.OK)
{
string path = dialog.FileName;
playSound(path);
}
5.Add the following method code under the button1_Click event hander.
private void playSound(string path)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer();
player.SoundLocation = path;
player.Load();
player.Play();
}
6.Now let's run the application just by Pressing the F5 to run the code.
7.Click the button and select an audio file. After the file loads, the sound will play.
I hope this is useful example to beginners...
I think you must firstly add a .wav file to Resources. For example you have sound file named Sound.wav. After you added the Sound.wav file to Resources, you can use this code:
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.Sound);
player.Play();
This is another way to play sound.

Silverlight media player

I am using VSTS 2008 with C# to develop Silverlight application embedded in web page of an ASP.Net web application. I have embedded in XAML a MediaElement item. My question is, I want to embed the page a Silverlight media player, which could let end user to control the MediaElement item manually to -- play/pause/stop/rewind/forward. Are there any references samples?
thanks in advance,
George
EDIT1: add more accurate requirements,
Actually, I want to control play manually, which means I want to handle the player play/pause/stop/rewind/forward events and add my code for the event handlers to control the MediaElement and do something else.
EDIT2: My needs are, I want to play two overlapped video. Screen as background video and camera as foreground video (place at right bottom corner). Here is my modification of code, my current issue is, only background video is played, foreground right bottom video is never played. Does anyone have any ideas why?
BTW: my modified code and current work is based on http://www.codeplex.com/sl2videoplayer
http://www.yourfilehost.com/media.php?cat=other&file=sl2videoplayer_24325_new.zip
Here is a brief description of my major modified code,
mediaControls.xaml.cs
private MediaElement _media = null;
private MediaElement _camera = null;
public MediaElement Camera
{
set
{
_camera = value;
}
}
void btnPlay_Checked(object sender, RoutedEventArgs e)
{
_camera.Play();
_media.Play();
OnPlayClicked();
}
Page.xaml
<MediaElement HorizontalAlignment="Stretch" Margin="0,0,0,0" x:Name="mediaPlayer" Stretch="Uniform" VerticalAlignment="Stretch" AutoPlay="false"/>
<MediaElement Width="100" Height="100" x:Name="cameraPlayer" AutoPlay="false" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
Page.xaml.cs
cameraPlayer.Source = App.Current.Resources["c"] as Uri;
App.xaml.cs (Application_Startup function)
else if (item.Key.ToLower() == "c")
{
FormatUri(e.InitParams["c"].ToString(), "c", false);
}
default.html
<param name="initParams" value="cc=true,markers=true,markerpath=markers_movie21.xml,m=http://localhost/screen.wmv,c=http://localhost/camera.wmv" />
Oh baby have I got the media player for you: Sl2 Video Player. MSPL open sourced and awesome.
To add the ability to control the player pragmatically, add ScriptableMembers.
You'll see the registration statement already in the code:
HtmlPage.RegisterScriptableObject("Page", page);
Now look at an example ScriptableMember:
[ScriptableMember]
public void SeekPlayback(string time)
{
TimeSpan tsTime = TimeSpan.Parse(time);
mediaControls.Seek(tsTime);
}
already exists in the code. Add more methods to do what you want to have happen. Then you can call the methods from managed code in another SL player:
HtmlElement videoPlugin = HtmlPage.Document.GetElementById("VideoPlayer");
if (videoPlugin != null)
{
ScriptObject mediaPlayer = (ScriptObject)((ScriptObject)videoPlugin.GetProperty("Content")).GetProperty("Page");
mediaPlayer.Invoke("SeekPlayback", TimeSpan.FromSeconds(seconds).ToString());
}
or from javascript:
var sl = document.getElementById("VideoPlayer");
var content = sl.Content.Page;
content.SeekPlayback('55');
If they are two seperate xap packages, there will be no way for the two to communicate since Silverlight sandboxes both individually.
SL2videoplayer says it supports streaming video. But when I try giving a media services broadcast url (OnDemand and Live) to init param 'm' nothing showed up. In the init param example page also a remote wmv file being played is shown.
Also are there any known issues of using this with SL 3?

Categories

Resources