Windows Phone 8.1: MediaElement not Playing after Frame.Navigate - c#

I started building my own Windows Phone 8.1 App. I implemented a mp3 file. Whenever I implement it on the main page in the XAML
<MediaElement x:Name="GoalHorn" Source="/Sounds/mySound.mp3" AutoPlay="False" Visibility="Visible"></MediaElement>
I can call it in the source code and start it by
GoalHorn.Play()
I now wanted to put it on another frame. I used:
Frame.Navigate(typeof(ScoredPage)), scorerBox.Text);
However, when I want to start the sound on the new frame, nothing is done when calling
GoalHorn.Play()
I have it in the XAML of the new Frame aswell. When I set the autoplay to "true", it also works on the frame but I can't stop it.
Can anybody help?

It happens when media is not opened/loaded still and .Paly method is called on the media element. Add MediaOpened event handler and call play method in it.
<MediaElement MediaOpened="GoalHorn_MediaOpened" x:Name="GoalHorn" Source="/Sounds/mySound.mp3" AutoPlay="False" Visibility="Visible"></MediaElement>
Event handler
private void GoalHorn_MediaOpened(object sender, RoutedEventArgs e)
{
GoalHorn.Play();
}

Related

playing media element when lock screen xamarin forms

I am Using Xamarin forms for play some music , when I lock my phone, the audio will stop. how should I Handel ? I do not want music pause
{
MediaElement KeepScreenOn="True" x:FieldModifier="Public" Source="Voice.mp3" AutoPlay="False" ShowsPlaybackControls="True" x:Name="MyMedia"
}
MediaElement is currently experimental, I cannot found this feature play the music when lock screen, but you can use CrossMediaManager, It is support the play the music when lock screen by default.
Just Used a Button to invoke the play method.
<Button Text="play" Clicked="Button_Clicked"></Button>
private async void Button_Clicked(object sender, EventArgs e)
{
await CrossMediaManager.Current.Play("https://ia800806.us.archive.org/15/items/Mp3Playlist_555/AaronNeville-CrazyLove.mp3");
}
Note:when add CrossMediaManager.Current.Init(this); in your OnCreate method of MainActivity.cs. Please do not forget the set the Target Framework to Android 9.0 or later.

MediaPlayer Universal Windows App

I started to develop application using xamarin, and one of projects inside my solution is UWP.
I need to play sound there when someone clicked button, I'm using MediaPlayer to achieve my goal, and on windows 10 (desktop) it works fine, but on my Windows Mobile 10 (Lumia 930) it starts with long delay (about 1 second).
Below I provide my code to play audio source:
MediaPlayer _player = BackgroundMediaPlayer.Current;
_player.SetUriSource(new Uri(String.Format("ms-appx:///Assets/Sound/5s.wav", UriKind.Absolute)));
_player.Play();
My Question is:
Is there any other way to play audio in UWP than MediaPlayer?
If you don't have specific reason to use background audio, you can use just media element to play audio in foreground:
<!-- create element in XAML or in code -->
<MediaElement Name="mediaElement" ... />
// Code - set source or reference to stream
MediaElement mediaElement = new MediaElement();
mediaElement.Source = new Uri("msappx:///Media/sound.mp3");
I would also recommend to check with the list of supported codecs.
In more complex scenarios you may want to look at Audio Graph API.
I'm not sure if this is bad practice or not, but I am able to get instant playback if I pre-load the media.
Something like this example in pseudo-code (c# style):
class Foo
{
private MediaPlayer _player;
Foo() //constructor
{
_player = BackgroundMediaPlayer.Current;
_player.AutoPlay = false;
_player.SetUriSource(new Uri(String.Format("ms-appx:///Assets/Sound/5s.wav", UriKind.Absolute)));
}
void ButtonClicked(Object sender, EventArgs event)
{
_player.Play();
}
}

Use the MediaElement cause the error "The background audio resources are no longer available."

In my app, I have to use an AudioPlaybackAgent (APA) and a mediaelement. I used the APA to play songs , and when I need to play video, I use the MediaElement
When I navigate to a page use the MediaElement, I stop the BackgroundAudioPlayer:
BackgroundAudioPlayer.Instance.Pause();
When I navigate back to a page which need to play music, I call the APA to start again, but now it return the exception "The background audio resources are no longer available." :(
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
try
{
if (BackgroundAudioPlayer.Instance.PlayerState != PlayState.Playing)
BackgroundAudioPlayer.Instance.Play();
}
catch
{
BackgroundAudioPlayer.Instance.Play();
}
}
I can use the MediaPlayerLauncher , but this solution has many disvantage (only fullscreen, lack of my custom control ...).
So is there any way to make the media element work along with the AudioPlaybackAgent, or any other way to playing video ???
This occurs because data get lost when navigating between pages. You can try saving data to IsolatedStorage.
You can find more information in this question:
Save values between page navigation in Windows Phone

How can I navigate through xaml pages with Monogame in a Windows Phone 8 project?

I finished to develop an XNA game, then I created the Monogame project, and tested it on my device. Now I made some other pages such as an "about" page. How can I go to that page considering I have a Monogame project and just an XNA code? In particular inside my game I made a Main Menu where you can click the "about" button and know if someone has clicked: how can I link that event to the "go to about.xaml" function?
Inside XNA, update method:
if (about_button.IsClicked())
{
// Go to about.xaml
}
I tried:
if (about_button.IsClicked())
{
((PhoneApplicationFrame)Application.Current.RootVisual).Navigate(new Uri("/About.xaml", UriKind.Relative));
}
But it throws: System.UnauthorizedAccessException
I haven't tried this myself, but the WP framework has the Window.Current.Content object which you can use to load different views.
For example:
// Create a Frame to act navigation context and navigate to the first page
var rootFrame = new Frame();
rootFrame.Navigate(typeof(BlankPage));
// Place the frame in the current Window and ensure that it is active
Window.Current.Content = rootFrame;
Window.Current.Activate();
So if you are using a windows phone 8 project template, with that object you can easily tell the application to load a xaml view or the game one.
You can also check how to do it with WinRT and monogame on this site (the Window.Current is part of the WP and WinRT framework). Here, you will find how to integrate both frameworks in order to create a monogame using the WinRT xaml views :)
For more information on the Window.Current, check this link.
EDIT
If you used a monogame for windows phone template, a XAML page should already exist in your project which is used to load the game itself, as well as a media element for video and sound playback.
The page is called "GamePage.xaml", which you could use for your navigational purposes.
This info was taken from the "Windows 8 and Windows Phone 8 Game Development" book written by Adam Dawes (chapter 13).
In the case of the Windows Phone projects, GamePage is implemented as
a normal page. [...]
Within the Windows Phone page is a full-page
Grid control, inside which is another full-screen control of type
DrawingSurface. This is a type of control that DirectX can use to
render graphics to a Windows Phone page. Our XAML content can also be
placed into the Grid. A MediaElement control is present within the
Grid, too. MonoGame uses this for some of its audio playback
functionality.
On both platforms, the way that XAML and DirectX have been designed to
interact is that the DirectX rendering is processed first. Once this
has been completed, the XAML renderer then takes control and adds its
content as a second step, prior to presenting the final rendered page
to the user. As a result, XAML content will always appear in front of
any graphics rendered by MonoGame. This ensures that any XAML controls
we use as our user interface (for control buttons, text displays, and
so on) will appear unobstructed in front of the game graphics.
The XAML rendering still takes any transparency within the controls
into account, so it is quite possible to have controls that are
partially transparent or that use alpha shading. These will blend in
front of the MonoGame graphics, as you would expect them to.
With this into account, you should be able to throw an event from your game class (monogame), the xaml page can suscribe itself to it and then, when captured, render your xaml page (maybe a user control would be wiser as you won't navigate away from the main game page).
Hopefully, this will help you with your problem.
Try to create a frame in your gamepage
public static Frame RootFrame { get; private set; }
then in your click event put these lines
RootFrame = new Frame();
RootFrame.Navigate(typeof(about));
did this work?
You receive that error because the call has to be made from the UI thread like this:
Deployment.Current.Dispatcher.BeginInvoke(() =>
(App.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/Pages/MenuPage.xaml", UriKind.Relative)));
Also, make sure you dispose of the game object when unloading the game xaml page. You to this by subscribing to the Unloaded event of the GamePage and calling Dispose on the game object. See below:
public partial class GamePage : PhoneApplicationPage
{
private LoonieGame _game;
public GamePage()
{
InitializeComponent();
_game = XamlGame<LoonieGame>.Create("", this);
this.Unloaded += GamePage_Unloaded;
}
void GamePage_Unloaded(object sender, RoutedEventArgs e)
{
Deployment.Current.Dispatcher.BeginInvoke(() => _game.Dispose());
}
}

Windows Phone MediaElement

I am creating an app using c# and xaml where i have 20 pages each page has some character images and when i tap on that image some dialogues should pop up.so i have taken a MediaElement and made it global like this:
App.xaml:
<MediaElement x:Key="StorySound"
Volume="1"
AutoPlay="True"/>
App.xaml.cs:
public static MediaElement StorySound
{
get { return Current.Resources["StorySound"] as MediaElement; }
}
And on every page on tap event i have written this code:
App.StorySound.Source = new Uri("/Sounds/Dialogues/" + textblock.Text + ".mp3", UriKind.Relative);
App.StorySound.MediaOpened+=StorySound_MediaOpened;
void StorySound_MediaOpened(object sender, RoutedEventArgs e)
{
App.StorySound.Play();
}
This plays the sound on not more than 2 pages when i navigate to the 3rd page using the next button which i have created no sound plays but when i close the app and directly open the 3rd page the sound plays.I have even tested this by using MessageBox to show the current state of the mediaelement i have found that on the first two pages the current state is "Opening" and the sound plays but on the third page the current state is "Closed" so the sound does not Play.is there any memory issue when playing sounds using MediaElement.I cannot use SoundEffect Because all my sound files are .mp3 and if i use soundeffect i will have to convert these sounds in .wav which will increase the size of my app because i have more than 50 sound files.
If I understand you correctly you are hooking the MediaOpened-event on the global StorySound-object on each page but you never seem to unhook it.
I would suggest you to either:
use a local MediaElement on each page that you start (and perhaps stop), or
make sure you unhook all events on the StorySound when you navigate (so that each page is the only "user" of this global resource).
I am sure it will be fine to have may mp3's in your app; you should not need to convert them to wav.

Categories