Windows 8 store app MediaElement events not firing - c#

I've developing a Windows 8 app in Visual Studio 2012 ultimate but i'm having an issue with the MediaElement where the MediaOpened and MediaEnded events are not being fired.
Below is my code:
public static async void PlaySound(string AudioFile, RoutedEventHandler PlayerEnded)
{
Uri audioUri = new Uri("ms-appx:///Assets/" + AudioFile);
StorageFile audioStorage = await StorageFile.GetFileFromApplicationUriAsync(audioUri);
if (audioStorage != null)
{
var stream = await audioStorage.OpenAsync(Windows.Storage.FileAccessMode.Read);
MediaElement player = new MediaElement();
player.AudioCategory = AudioCategory.GameEffects;
player.AutoPlay = false;
player.MediaEnded += PlayerEnded;
player.MediaOpened += new RoutedEventHandler(delegate(Object sender, RoutedEventArgs e)
{
player.Play();
});
player.SetSource(stream, audioStorage.ContentType);
}
}
Basically this will be passed a button click sound file which after finish playing will call the this.Frame.Navigate method to switch to another page. But it doesn't work since none of the events are being fired.
If I set AutoPlay = true then it plays fine, but then events still don't get fired.
Can anyone see what is wrong?
Thanks for your help

I think your MediaElement needs to be in the visual tree to fire.
See http://social.msdn.microsoft.com/Forums/en-US/winappswithnativecode/thread/f5b9cdba-5521-467d-b838-8420afc68e7f/

Related

UWP app crash when trying to open File Picker from WebView ScriptNotify even when running by Dispatcher

Reproducible repo here
My app has a WebView for UI and it notifies the backend code by using window.external.notify:
public MainPage()
{
this.InitializeComponent();
this.web.ScriptNotify += this.Web_ScriptNotify;
this.web.Navigate(new Uri("ms-appx-web:///index.html"));
}
private void Web_ScriptNotify(object sender, NotifyEventArgs e)
{
_ = this.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
async () =>
{
var d = new FileOpenPicker();
// Changing UI text is okay
this.lbl.Text = "Hello!";
// Crash here:
var file = await d.PickSingleFileAsync();
});
}
One of the command I want to do is to open a File Picker. However, it crashes with this exception System.Runtime.InteropServices.COMException: 'Unspecified error'. I thought it is because I tried to open it from outside UI thread, so I run it in a Dispatcher already but it still happens.
What should I do?
It crashes because I didn't set FileTypeFilter, not because of the event. Adding this helps:
diagOpen.FileTypeFilter.Add("*");

The SystemMediaTransportControls were initialized in a different mode error in mytoolkit

When i run mytoolkit after background audio player start is return "The SystemMediaTransportControls were initialized in a different mode. Please use the API associated with that mode to complete this operation" Exception.
var url = await MyToolkit.Multimedia.YouTube.GetVideoUriAsync(ID, MyToolkit.Multimedia.YouTubeQuality.Quality480P);
it works fine when background audio player not started. please help me i cant find where is the error, is there any solution for that...
In your code for background audio player use
var systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
systemMediaControls.ButtonPressed += systemMediaControls_ButtonPressed;
systemMediaControls.IsPlayEnabled = true;
systemMediaControls.IsPauseEnabled = true;
systemMediaControls.IsNextEnabled = true;
systemMediaControls.IsPreviousEnabled = true;
async void systemMediaControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Play:
break;
}
}
instead of
MediaControl.PlayPressed += MediaControl_PlayPressed;
MediaControl.PausePressed += MediaControl_PausePressed;
Control.
I think it will help for you..
Did you follow the directions as this guy did for windows 8 and not for 8.1?
"Do NOT use the MediaControl static class to attach handlers for you Windows 8.1 app or you will get the error message"

Windows phone 8.1 universal app DataTransferManager UI not showing

In my windows phone 8.1 universal app project I am trying to make a share option.
But when I click on the button (ShareCommand) the Share UI is not showing up, I have tried this in the emulator and on a device.
The event is correctly wired up since the DataRequested event gets called, but after this event there is no Share UI showing.
Here is the code I use in my ViewModel (using prism framework).
private DataTransferManager _dataTransferManager;
private DelegateCommand _shareCommand;
// Share button
public DelegateCommand ShareCommand
{
get
{
return _shareCommand ?? (_shareCommand = new DelegateCommand(() =>
{
DataTransferManager.ShowShareUI();
}));
}
}
public override async void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode, Dictionary<string, object> viewModelState)
{
base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);
// get data transfer manager and register events
_dataTransferManager = DataTransferManager.GetForCurrentView();
_dataTransferManager.DataRequested += DataTransferMangerDataRequested;
_dataTransferManager.TargetApplicationChosen += DataTransferMangerTargetApplicationChosen;
}
public override void OnNavigatedFrom(Dictionary<string, object> viewModelState, bool suspending)
{
base.OnNavigatedFrom(viewModelState, suspending);
// clean up events
_dataTransferManager.DataRequested -= DataTransferMangerDataRequested;
_dataTransferManager.TargetApplicationChosen -= DataTransferMangerTargetApplicationChosen;
}
private void DataTransferMangerTargetApplicationChosen(DataTransferManager sender, TargetApplicationChosenEventArgs args)
{
}
private void DataTransferMangerDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
var request = args.Request;
var deferral = request.GetDeferral();
request.Data.Properties.Title = "title test";
request.Data.Properties.Description = "description test";
request.Data.SetText("test hello");
request.Data.SetUri(new Uri("https://www.google.com"));
request.FailWithDisplayText("fail");
deferral.Complete();
}
I have tried setting different properties in the DataRequested event but still nothing.
Does anyone know what it could be? Do I need to set some permissions?
Edit:
Ok, weird I tried this in a new solution with only this code and it is working fine. But no idea why its not working in my current solution.
Ok I found out what was causing the problem.
I had to remove this, since this will cancel the operation. (I thought this will show if it failed for some reason and not cancel directly).
request.FailWithDisplayText("fail");

Streaming mp3 file from external server

I am developing a Windows Phone 8 application. I need to stream a .mp3 sound file from a remote server in my application.
I have tried to use MediaElement:
private MediaElement media;
// Constructor of class
media = new MediaElement();
media.Source = new Uri(string.Format("{0}b10en_US.mp3", mp3HostName), UriKind.Absolute);
media.MediaFailed += media_MediaFailed;
media.MediaEnded += media_MediaEnded;
media.MediaOpened += media_MediaOpened;
media.Loaded += media_Loaded;
media.BufferingProgressChanged += media_BufferingProgressChanged;
// In a method I call the following
media.play();
However no sound gets played whatsoever. I added breakpoints to the mediaelement's events, but none gets fired.
I have double checked, the URI to the mp3 file is correct.
What am I doing wrong?
You can play mp3 after media opened event is raised. I think your method(in which you are calling play is called before media opened event is raised.
you can implement some hack in mediaOpened event and your method(play). like
private bool isMediaLoaded = false;
private bool isPlayCalled = false;
private void PlayMP3()
{
if(isMediaLoaded)
media.Play();
else
isPlayCalled = true;
}
void MediaElement1_MediaOpened(object sender, RoutedEventArgs e)
{
isMediaLoaded = true;
if(isPlayCalled)
MediaElement1.Play();
}
Try this :
string url = "http://traffic.libsyn.com/slashfilmcast/Davidmichod.mp3";//your url link
// Constructor
public MainPage()
{
InitializeComponent();
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
Song track = Song.FromUri("Sample Song", new Uri(url));
MediaPlayer.Play(track);
}
using Microsoft.Xna.Framework.Media; //for getting MediaPlayer

Windows Phone 8 canĀ“t call AudioVideoCaptureDevice second time

In my App you can open a Site where you can switch on and off the Flashlight.
The first time it works, but if I try to switch the flashlight on a second time the App crashes.
I think this is a Problem with AudioVideoCaptureDevice.OpenAsync. If I call it a second time the App crashes with a System.Reflection.TargetInvocationException WinRT-Informationen: Unable to acquire the camera. You can only use this class while in the foreground.
Someone know this Problem?
protected AudioVideoCaptureDevice Device { get; set; }
public Page10()
{
InitializeComponent();
}
async void tglSwitch_Checked(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
if (this.Device == null)
{
// get the AudioVideoCaptureDevice
this.Device = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
}
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
this.tglSwitch.Content = "Light on";
this.tglSwitch.SwitchForeground = new SolidColorBrush(Colors.Green);
}
}
void tglSwitch_Unchecked(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
sensorLocation = CameraSensorLocation.Back;
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (this.Device != null && supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.Off))
{
this.Device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
this.tglSwitch.Content = "Light off";
}
}
I would recommend to initialize the camera with OpenAsync ONE TIME in page lifecycle, for example in OnNavigatedTo event. And only makeSetProperty() methods calls code in your checkbox events to control light. It is also very important to dispose camera correctly then leaving the page, for example in OnNavigatedFrom event, by calling device.Dispose(). This option also make your flashlight to work faster.
Keep in mind that Windows Phone 8.1 now has dedicated API for torch, which works great and the code is more beautiful. You can use in Silverlight project as well, but you have to migrate your project. Here is more about this http://developer.nokia.com/community/wiki/Using_the_camera_light_in_Windows_Phone_7,_8_and_8.1 and https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.devices.torchcontrol.

Categories