Audio and Video playing in Windows 10 universal app? - c#

I need to play audio and video in windows app where I Get the Url from networkcall and I need to add Url to Source.
I tried in this way, But no video is played or audio is played.
Someone help me in how to achieve this?
Is there any other way to achieve this?
Thanks in Advance.
My xaml code:
<StackPanel HorizontalAlignment="Center" Grid.Row="3">
<MediaElement x:Name="media"
Source="Videos/video1.mp4"
Width="400"
AutoPlay="False"
AreTransportControlsEnabled="True" />
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
<Button Content="Play" Click="Play_Click"/>
<Button Content="Pause" Click="Pause_Click"/>
<Button Content="Stop" Click="Stop_Click" />
</StackPanel>
</StackPanel>
My cs code:
async void Play_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Uri pathUri = new Uri("https://www.youtube.com/watch?v=sOEg_YZQsTI");
media.Source = pathUri;
Util.debugLog("PLaying ...");
media.Play();
media.Volume = 40;
});
}
async void Pause_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Util.debugLog("Paused .. ");
media.Pause();
});
}
async void Stop_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Util.debugLog("Stoped ..");
media.Stop();
});
}
void Media_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
// Handle failed media event
}
void Media_MediaOpened(object sender, RoutedEventArgs e)
{
// Handle open media event
}
void Media_MediaEnded(object sender, RoutedEventArgs e)
{
// Handle media ended event
}

If I get it right you are currently assigning a website as the source of the MediaElement. That can't work. If you want to embed youtube content you have two possibilities:
Embed the webpage in a WebView
Set the url to the video itself as the Source

Related

UWP C# Switching frame content issues and crashes

I've struggled with this setup for couple of days and found a somewhat solution but I think it not how it supposed to work.
Here is my xaml page setup:
<Page
...
<SplitView IsPaneOpen="True" DisplayMode="Inline" OpenPaneLength="300">
<SplitView.Pane>
<Grid>
<ToggleButton x:Name="Edit" IsEnabled="False" Checked="Edit_Checked" Unchecked="Edit_Unchecked"/>
</Grid>
</SplitView.Pane>
<Frame x:Name="RightFrame">
</Frame>
</SplitView>
</Page>
Code for toggle button:
private void Edit_Checked(object sender, RoutedEventArgs e)
{
RightFrame.Navigate(typeof(SubPage1));
}
private void Edit_Unchecked(object sender, RoutedEventArgs e)
{
RightFrame.Navigate(typeof(SubPage2));
}
So basically the toggle button switches the splitview content. The SubPages are just blank pages. The problem is that app crashes when navigation occurs.
I've noticed when I put this before invoking navigation:
RightFrame.Content = null;
Thread.Sleep(1000);
Then everything works fine. So I need to clear frame content and wait for it to finish I guess. But I think it should be done automatically. Could some one explain what am I doing wrong here and how it should be done?
Please verify your code in SubPage1 and SubPage2 which might be creating the crashes, you can clear the resources when the page gets unloaded.
Alternatively, you can try below code:
private void Edit_Checked(object sender, RoutedEventArgs e)
{
RightFrame.Content = new SubPage1();
}
private void Edit_Unchecked(object sender, RoutedEventArgs e)
{
RightFrame.Content = new SubPage2();
}

How to pause MediaElement when single tap/touch on the screen - UWP

I have to play a video using MediaElement. I want to pause the video when the user taps the screen. I found that there is double tapped event on MediaElement, but couldn't find any single touch event. How can I do this?
<MediaElement Name="videoMediaElement" AreTransportControlsEnabled="True" Stretch="Fill"
MediaOpened="videoMediaElement_MediaOpened" CurrentStateChanged="Media_State_Changed">
<MediaElement.TransportControls>
<MediaTransportControls Background="Red" Foreground="White"
IsStopButtonVisible="True" IsStopEnabled="True" IsTextScaleFactorEnabled="True"
IsPlaybackRateEnabled="True" IsPlaybackRateButtonVisible="True"
IsFastForwardButtonVisible="True" IsFastForwardEnabled="True"
IsFastRewindButtonVisible="True" IsFastRewindEnabled="True"/>
</MediaElement.TransportControls>
</MediaElement>
private async void Media_State_Changed(object sender, RoutedEventArgs args)
{
if (videoMediaElement.CurrentState == MediaElementState.Paused)
{
}
}
There are plenty of events you can use for that, e.g. the MouseLeftButtonDown or TouchDown events. It's as simple as that:
private void element_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
((MediaElement)sender).Pause();
}
private void element_TouchDown(object sender, System.Windows.Input.TouchEventArgs e)
{
((MediaElement)sender).Pause();
}
By #JetChopper:
private void element_PointerPressed(object sender, PointerRoutedEventArgs e)
{
((MediaElement)sender).Pause();
}

MediaElement.Position not reflecting on changes in UWP

I have a MediaElement whose position when set is not reflecting.
if(Playback.CanSeek)
Playback.Position = new TimeSpan(0,0,4);
Do note the MediaElement is currently paused and Autoplay turned on etc.
There are no errors but the line just does not change the Position property.
Also ran the code in Core Dispatcher, but still no luck.
Edit: Also Note this MediaElement is created from C# and not associated with XAML as it is in the ViewModel as a Library.
Thank you.
To solve this issue, you would have to add your MediaElement object into XAML UI.
For example like the following code:
<Grid x:Name="root" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button Content="set" Click="Button_Click"></Button>
</Grid>
MediaElement playback = new MediaElement();
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var file = await Package.Current.InstalledLocation.GetFileAsync("test.mp3");
if (file != null)
{
var stream = await file.OpenReadAsync();
playback.SetSource(stream, file.ContentType);
}
playback.Play();
root.Children.Add(playback);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (playback.CanSeek)
{
playback.Position = TimeSpan.FromSeconds(5);
}
}

Cannot play media Element programmatically

I developed an app in Windows Phone 8. I have a list with mp3 from web and a mediaelement can't play them.
This is my code
private void Button_Click_1(object sender, RoutedEventArgs e)
{
play.Source = new Uri("http://n1.xtek.gr/ime_ploigos/rest/narrations/gr/10.mp3",UriKind.RelativeOrAbsolute);
play.MediaOpened += new RoutedEventHandler(note1_MediaOpened);
}
void note1_MediaOpened(object sender, RoutedEventArgs e)
{
play.Play();
}
And xaml is :
<MediaElement HorizontalAlignment="Left" Height="100" Margin="167,538,0,0" VerticalAlignment="Top" Width="100" Name="play" AutoPlay="True"/>
I have try it in xaml and play it but programmatically not. Can someone help me ?
I do not think you need to Play inside MediaOpened event. Just execute .Play after assigning Source to the MediaPlayer
Just add this to button click event
private void Button_Click_1(object sender, RoutedEventArgs e)
{
play.Source = new Uri("http://n1.xtek.gr/ime_ploigos/rest/narrations/gr/10.mp3",UriKind.RelativeOrAbsolute);
play.Play();
}

How do I navigate to a new page in windows 8 metro apps after the sound is finished playing?

I'm using the following code to play sound on a button click.
public class AudioHelper
{
public async static void playButtonClick()
{
MediaElement snd = new MediaElement();
StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("Audios");
StorageFile file = await folder.GetFileAsync("buttonClick.m4a");
var stream = await file.OpenAsync(FileAccessMode.Read);
snd.SetSource(stream, file.ContentType);
snd.Play();
}
}
I called the code from the button click event using the following codes:
private void btnFlashCard_Click(object sender, RoutedEventArgs e)
{
AudioHelper.playButtonClick();
this.Frame.Navigate(typeof(LevelSelection));
}
since the playButtonClick is async, the page navigate to the LevelSelection page before the audio start playing. How do I make it so that the audio play first then the page navigate? Thank you.
EDIT:
Thanks to #htcdmrl I was able to figure out how to do this. As I mentioned in the comment, in order for the MediaEnded event to fire, the MediaElement has to be in the visual tree. I added the following code in the xaml and modify the code slightly to get it to work.
I added the following code to XAML:
<Frame HorizontalAlignment="Left" Margin="10,742,0,0" VerticalAlignment="Top">
<MediaElement x:Name="me" HorizontalAlignment="Left" Height="100" Margin="20,742,0,-74" VerticalAlignment="Top" Width="100" RenderTransformOrigin="0.359,-0.219"/>
</Frame>
Added the following codes to MainPage.Xaml.cs
public MainPage()
{
this.InitializeComponent();
me.MediaEnded += me_MediaEnded;
}
void me_MediaEnded(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(LevelSelection));
}
and change playButtonclick and btnFlashCard_Click to the following:
private void btnFlashCard_Click(object sender, RoutedEventArgs e)
{
playButtonClick();
}
public async void playButtonClick()
{
StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("Audios");
StorageFile file = await folder.GetFileAsync("buttonClick.m4a");
var stream = await file.OpenAsync(FileAccessMode.Read);
me.SetSource(stream, file.ContentType);
me.Play();
}
Add media ended event to your media element;
MediaElement snd = new MediaElement();
snd.MediaEnded += snd_MediaEnded;
Then add your event;
void snd_MediaEnded(object sender, RoutedEventArgs e)
{
snd.Stop();
this.Frame.Navigate(typeof(LevelSelection));
}
Use Event MediaElement.MediaEnded Event:
private void btnFlashCard_MediaEnded(object sender, EventArgs e)
{
this.Frame.Navigate(typeof(LevelSelection));
}

Categories