Windows Phone 7 with Silverlight - MediaElement doesn't play with this code - windows-phone-7

What am I doing wrong please?
it doesn't show any error, and doesn't play.
MediaElement song = new MediaElement();
song.Source = new Uri(#"\WP7_aaa\WP7_aaa\GameSounds\MenuScreen.mp3", UriKind.Relative);
LayoutRoot.Children.Add(song);
song.AutoPlay = false;
song.Play();

In your project, for the MP3 file, have you -
set the Build Action property to Content?
set the Copy To Output Directory to Copy Always?
In case you haven't done the above in the project, try them out.
HTH, indyfromoz

You need to wait for the song to be loaded before you can call the Play method on it.
What you want is:
MediaElement song = new MediaElement();
song.Source = new Uri("Audio/background.mp3", UriKind.Relative);
song.MediaOpened += MediaElement_MediaOpened;
And then in the event handler:
private void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
(sender as MediaElement).Play();
}
See this thread for more details. (edit: no idea where to find this thread now that they split it into WP and Xbox Forums...)

You must specify kind of Uri as RelativeOrAbsolute.
MediaElement song = new MediaElement();
song.Source = new Uri(#"\WP7_aaa\WP7_aaa\GameSounds\MenuScreen.mp3", UriKind.RelativeOrAbsolute);
LayoutRoot.Children.Add(song);
song.AutoPlay = false;
song.Play();

Related

How to open native video player to play local contents in Xamarin forms

I have some video file embedded with the project, that to be opened in the native video player using Xamarin forms.
Note: Having in-app video player is limited here.
Any idea for this?
Sorry for late, you could refer to FormsNativeVideoPlayer.
When you load your video file from Raw folder, you just need to modify the VideoPlayer_CustomRenderer code like this :
protected override void OnElementChanged (ElementChangedEventArgs<Xamarin.Forms.View> e)
{
base.OnElementChanged (e);
...
string uriPath = "android.resource://" + Forms.Context.PackageName + "/" + Resource.Raw.audio;
var uri = Android.Net.Uri.Parse((uriPath));
//Set the videoView with our uri, this could also be a local video on device
videoView.SetVideoURI (uri);
...
}

Geofence is not being triggered in the background in windows phone 8.1

I'm trying to implement geofencing in Windows phone 8.1. First I wanted to create a sample Project to understand how it Works, but i couldnt make it works. What I'm trying to achieve is basically, I'll set the coordinates and close the app by pressing back button and it will trigger a toast notification when the phone is in the area of interest.
I've created a blank Windows phone(silverlight) 8.1 Project(geofence_test_01) and added a Windows RT Component Project(BackgroundTask) into the same solution. Added a reference for BackgroundTask in the geofence_test_01 Project.
ID_CAP_LOCATION is enabled in the app manifest.
MainPage.xaml has only one button to start geofencing.
<Button Name="btnStart" Content="Start" Click="btnStart_Click"/>
In btnSave_Click, I call a method which creates the geofence and registers the background task.
private void btnStart_Click(object sender, RoutedEventArgs e)
{
Init_BackgroundGeofence();
registerBackgroundTask();
}
private async Task Init_BackgroundGeofence()
{
//----------------- Crating Geofence ---------------
var geofenceMonitor = GeofenceMonitor.Current;
var geoId = "building9";
var positionBuilding9 = new BasicGeoposition()
{
Latitude = 47.6397,
Longitude = -122.1289
};
var geofence = new Geofence(geoId, new Geocircle(positionBuilding9, 100),
MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited,
false, TimeSpan.FromSeconds(10));
geofenceMonitor.Geofences.Add(geofence);
}
private async Task registerBackgroundTask()
{
//----------------- Register Background Task ---------------
var backgroundAccessStatus =
await BackgroundExecutionManager.RequestAccessAsync();
var geofenceTaskBuilder = new BackgroundTaskBuilder
{
Name = "GeofenceBackgroundTask",
TaskEntryPoint = "BackgroundTask.GeofenceBackgroundTask"
};
var trigger = new LocationTrigger(LocationTriggerType.Geofence);
geofenceTaskBuilder.SetTrigger(trigger);
var geofenceTask = geofenceTaskBuilder.Register();
}
And finally, in BackgroundTask, I've the following code:
namespace BackgroundTask
{
public sealed class GeofenceBackGroundTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
var geofenceMonitor = GeofenceMonitor.Current;
var geoReports = geofenceMonitor.ReadReports();
var geoId = "building9";
foreach (var geofenceStateChangeReport in geoReports)
{
var id = geofenceStateChangeReport.Geofence.Id;
var newState = geofenceStateChangeReport.NewState;
if (id == geoId && newState == GeofenceState.Entered)
{
//------ Call NotifyUser method when Entered -------
notifyUser();
}
}
}
private void notifyUser()
{
var toastTemplate = ToastTemplateType.ToastText02;
var toastXML = ToastNotificationManager.GetTemplateContent(toastTemplate);
var textElements = toastXML.GetElementsByTagName("text");
textElements[0].AppendChild(toastXML.CreateTextNode("You are in!"));
var toast = new ToastNotification(toastXML);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
}
}
I get no error when building and deploying this in the emulator. I set a breakpoint in the backgroundTask but I've not seen that part of code is called yet. It never hits the breakpoint. I test it by using Additional Tools of the emulator, in Location tab, by clicking somewhere in my geofence area on the map, waiting for a while, but it never hits the breakpoint. Hope somebody can tell me what i am missing here...
I've checked these following links to build this application:
http://www.jayway.com/2014/04/22/windows-phone-8-1-for-developers-geolocation-and-geofencing/
Geofence in the Background Windows Phone 8.1 (WinRT)
Toast notification & Geofence Windows Phone 8.1
http://java.dzone.com/articles/geofencing-windows-phone-81
Thanks
You can download the project here:
https://drive.google.com/file/d/0B8Q_biJCWl4-QndYczR0cjNhNlE/view?usp=sharing
---- Some clues
Thanks to Romasz, I've checked the Lifecycle events and i see "no background tasks" even after registerBackgroundTask() is executed.... Apparently there is something wrong/missing in registerBackgroundTask() method.
I've tried to build my sample (it was easier for me to build a new one) basing on your code and it seems to be working. You can take a look at it at my GitHub.
There are couple of things that may have gone wrong in your case:
remember to add capabilities in WMAppManifest file (IS_CAP_LOCATION) and Package.appxmanifest (Location)
check the names (of namespaces, classes and so on) in BackgroundTask
check if your BackgroundTask project is Windows Runtime Componenet and is added to your main project as a reference
I know you have done some of this things already, but take a look at my sample, try to run it and maybe try to build your own from the very beginning.
Did you add your background task in the Package.appxmanifest under Declarations with the correct supported task types (Namely Location)?

WP7: Get image's name which images are stored in Libary picture?

I have some images that are stored in Media Libary, view here. Now I need to get the name of an image after I choose the image by using photo chooser task. I used photo chooser task to select an image and then got the path of the image. My pupose is get the name from the path:
private void button1_Click(object sender, RoutedEventArgs e)
{
PhotoChooserTask objPhotoChooser = new PhotoChooserTask();
objPhotoChooser.Completed += new EventHandler<PhotoResult>(PhotoChooseCall);
objPhotoChooser.Show();
}
void PhotoChooseCall(object sender, PhotoResult e)
{
switch (e.TaskResult)
{
case TaskResult.OK:
BinaryReader objReader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
MessageBox.Show("Photo's name: " + e.OriginalFileName.ToString());
break;
case TaskResult.Cancel:
MessageBox.Show("Cancelled");
break;
case TaskResult.None:
MessageBox.Show("Nothing Entered");
break;
}
}
Output:
Photo's name: \Applications\Data\C80566AB-E17E-495C-81A1-3FCAE34D3DEDE\Data\PlatformData\PhotoChooser-a8208960-3597-40fc-9b4f-869afcf822b6.jpg
After I choose the same image. The name of it will change (PhotoChooser-a8208960-3597-40fc-9b4f-869afcf822b6.jpg will change). I think it's not the name of the photo.
So:
Can we get the name of the image?
And how do we do?
You can get the actual file names. Use the MediaLibrary for that:
MediaLibrary lib = new MediaLibrary();
var collection = lib.RootPictureAlbum;
foreach (var p in collection.Albums[0].Pictures)
Debug.WriteLine(p.Name);
Notice that I am specifying the album index inside the root picture album. 0 will be for sample pictures, and so on. If you need to grab the contents of the image, just use p.GetImage(); to get the readable stream.
No. You cannot get the name of the file as it is in the pictures hub. You are given a copy of the stream and that has a different, temporary, name.

Windows phone 7 - unable to play audio under lock screen

I am developing an app for windows phone 7. There is a media element which plays video from a url. When i lock the phone, the audio and video stops playing. I have tried disabling ApplicationIdleDetetction and i have handled Rootframe Obscured and Unobscured. I just couldn't figure out how to continue playing the audio when the phone is locked.
Any help on this is greatly appreciated !!
thanks
graham
Use the AudioPlayerAgent to keep the music playing even when the phone gets locked!
Check the "Background Audio Player Sample" on the Windows Phone Code Samples.
Video will automatically stop playing when the screen is locked - that is a built-in system feature. Think of it as a fail-safe for applications that will drain the device battery by playing video in the background, which is an unnecessary task anyway - who watches the content? ApplicationIdleDetection won't help with this task at all.
If you have a separate audio stream, you could use AudioPlayerAgent, that can be used to play both local and remote audio streams.
Read this:
Background Audio Overview for Windows Phone
How to: Play Background Audio for Windows Phone
Streaming Audio in Windows Phone
You can do this with a dispatcher timer. Here is an example of how I do it in my app Searchler (This feature not yet in marketplace, update coming very soon!) using the MMP Player Framework available # http://smf.codeplex.com/
namespace Searchler.Views
{
public partial class PlayerView : PhoneApplicationPage
{
bool appUnderLock = false;
DispatcherTimer dispatcherTimer = new DispatcherTimer();
}
public PlayerView()
{
InitializeComponent();
//Hack to enable play under lock screen
UIThread.Invoke(() => VideoPlayer.PlayStateChanged += VideoPlayer_PlayStateChanged);
UIThread.Invoke(() => (Application.Current as App).RootFrame.Obscured += RootFrame_Obscured);
UIThread.Invoke(() => (Application.Current as App).RootFrame.Unobscured += RootFrame_Unobscured);
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0, 0, 3);
}
void dispatcherTimer_Tick(object sender, EventArgs e)
{
if( VideoPlayer.PlaybackPosition == VideoPlayer.EndPosition)
((PlayerViewModel)DataContext).Next(); //Custom GetNext Video Method
}
void RootFrame_Unobscured(object sender, EventArgs e)
{
dispatcherTimer.Stop();
appUnderLock = false;
}
void RootFrame_Obscured(object sender, ObscuredEventArgs e)
{
dispatcherTimer.Start();
appUnderLock = true;
}
}

MediaElement Windows Phone 7

I'm creating a little app to help me better understand how to play sounds on WP7 devices but I'm having a problem actually getting the sound to come out of the device.
I have the following code:
<MediaElement x:Name="note1" Source="test.mp3" AutoPlay="False" />
private void btn1_Click(object sender, RoutedEventArgs e)
{
note1.Source = new Uri("test.mp3", UriKind.Relative);
note1.Play();
}
Where test.mp3's Build Action is a Resource.
The thing I don't understand is when I add a breakpoint on the method btn1_Click and I stop at note1.Play() it actually plays test.mp3 but when debug without breakpoints and click on the button I hear nothing.
Is there a way to fix this issue?
Have you tried playing with test.mp3's Build Action set as content.
Also did you close zune software after it recognizes the phone and completes sync, and connect using wp7connect tool. for more info about wp7connect tool try here.
zune locks all media on wp7 device and you cant play any media, but the status of the media will be "ended".
try setting up media's following events MediaFailed MediaOpened,MediaEnded, DownloadProgressChanged, CurrentStateChanged and BufferingProgressChanged
Also, make sure you have add the capability ID_CAP_MEDIALIB to your manifest (WMAppManifest.xml), this seems to be required for MediaElement (otherwise you'll get AG_E_NETWORK_ERROR in your MediaFailed handler).
i dont recommend mediaElement for more than one audio item ..it has weird effects ...use something like:
Stream stream = TitleContainer.OpenStream(#"Audio/buzzer.wav");
SoundEffect effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
effect.Play();
using the xna framework ....and make sure there WAV files.
Uri kind must be RelativeOrAbsolute.
private void btn1_Click(object sender, RoutedEventArgs e)
{
note1.Source = new Uri("test.mp3", UriKind.RelativeOrAbsolute);
note1.Play();
}
You need to make sure the MediaElement has been opened before you can call .Play() on it - you can do so by adding an event receiver to the MediaOpened event. It would also be good to call .Stop() any time prior to reassigning the Source property - take a look at this thread for more details.
This can't be solved without an Eventhandler. Do as mentioned below.
<MediaElement x:Name="note1" Source="test.mp3" AutoPlay="False" />
private void btn1_Click(object sender, RoutedEventArgs e)
{
note1.Source = new Uri("test.mp3", UriKind.Relative);
note1.MediaOpened += new RoutedEventHandler(note1_MediaOpened);
}
void note1_MediaOpened(object sender, RoutedEventArgs e)
{
note1.Play();
}
this is perfectly works. enjoy...

Resources