Pause Mediaelement in Windowos phone 8 if user navigates to the other app or homescreen - windows-phone-8

I had developed application which plays videos using MediaElement with remote url. Everything works fine videos are also playing nicely.
But the problem I am facing is if user is playing video and user touches windows button on phone. Then my app goes to background and home screen is displayed. now on home screen user touches back button. My app is brought to foreground and video starts loading from beginning. Is there anyway by which I can pause mediaelement so that when user comes back to my app video gets resumed.
One more thing is I can not user MediaLauncher since I want to log some events when user interacts with mediacontrols such as play/pause.
Kindly requesting you all to guide me in this scenario.
Thank You.

you can resume your application via ActivationPolicy attribute to the DefaultTask element inActivationPolicy attribute to the DefaultTask element in WMAppManifest.xml and set the value to “Resume”. For this task, you need to edit the app manifest directly instead of using the manifest editor. To do this, right-click WMAppManifest.xml, click Open with, and then choose XML (Text) Editor.
For Resume can be enabled for XAML apps, Direct3D apps, and Direct3D with XAML apps. The following examples show how the DefaultTask element will look for a XAML app and for a Direct3D app.
<DefaultTask Name="_default" NavigationPage="MainPage.xaml" ActivationPolicy="Resume"/>
<DefaultTask Name="_default" ImagePath="PhoneDirect3DApp1.exe" ImageParams="" ActivationPolicy="Resume"/>
app resume for Windows Phone 8
app resume backstack sample
If this will not help you than you can manual paly and stop your video pleyer like bellow code
XAML
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="0.90*"/>
<RowDefinition Height="0.10*"/>
</Grid.RowDefinitions>
<SSME:SmoothStreamingMediaElement x:Name="video" Grid.Row="0" />
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Orientation="Horizontal" Grid.Row="1">
<Button x:Name="PlayButton" Width="150" Click="PlayButton_Click" Loaded="PlayButton_Loaded"/>
<Button x:Name="StopButton" Content="Stop" Width="100" Click="StopButton_Click" />
<TextBlock x:Name="status"/>
<TextBlock x:Name="currentBitrate"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>
</Grid>
C# code:
public partial class VIdeoStraming : PhoneApplicationPage
{
string VideoUrl,StreamingUrl;
public VIdeoStraming()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
VideoUrl = this.NavigationContext.QueryString["parameter0"];
string Manifest="/Manifest";
StreamingUrl = VideoUrl + Manifest;
}
private void PlayButton_Click(object sender, RoutedEventArgs e)
{
//Monitor the state of the content to determine the right action to take on this button being clicked
//and then change the text to reflect the next action
switch (video.CurrentState)
{
case SmoothStreamingMediaElementState.Playing:
video.Pause();
PlayButton.Content = "Play";
break;
case SmoothStreamingMediaElementState.Stopped:
case SmoothStreamingMediaElementState.Paused:
video.Play();
PlayButton.Content = "Pause";
break;
}
}
private void PlayButton_Loaded(object sender, RoutedEventArgs e)
{
switch (video.AutoPlay)
{
case false:
PlayButton.Content = "Play";
break;
case true:
PlayButton.Content = "Pause";
break;
}
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
//This should simply stop the playback
video.Stop();
//We should also reflect the chang on the play button
PlayButton.Content = "Play";
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
video.CurrentStateChanged += new RoutedEventHandler(video_CurrentStateChanged);
video.PlaybackTrackChanged += new EventHandler<Microsoft.Web.Media.SmoothStreaming.TrackChangedEventArgs>(video_PlaybackTrackChanged);
//video.SmoothStreamingSource = new Uri("http://64.120.251.114:1945/live/sharedobjects/layoutvideo/mp4:1311370468970.MP4/Manifest");
video.SmoothStreamingSource = new Uri(StreamingUrl);
video.ManifestReady += new EventHandler<EventArgs>(video_ManifestReady);
}
//when use in mobile device
void video_ManifestReady(object sender, EventArgs e)
{
SmoothStreamingMediaElement ssme = sender as SmoothStreamingMediaElement;
if (ssme == null)
{
return;
}
// Select the highest band of tracks which all have the same resolution.
// maxMobileBitrate depends on the encoding settings
const ulong maxMobileBitrate = 1000000;
foreach (SegmentInfo segment in ssme.ManifestInfo.Segments)
{
foreach (StreamInfo streamInfo in segment.AvailableStreams)
{
if (MediaStreamType.Video == streamInfo.Type)
{
List<TrackInfo> widestBand = new List<TrackInfo>();
List<TrackInfo> currentBand = new List<TrackInfo>();
ulong lastHeight = 0;
ulong lastWidth = 0;
ulong index = 0;
foreach (TrackInfo track in streamInfo.AvailableTracks)
{
index += 1;
string strMaxWidth;
string strMaxHeight;
// If can't find width/height, choose only the top bitrate.
ulong ulMaxWidth = index;
// If can't find width/height, choose only the top bitrate.
ulong ulMaxHeight = index;
// V2 manifests require "MaxWidth", while v1 manifests used "Width".
if (track.Attributes.TryGetValue("MaxWidth", out strMaxWidth) ||
track.Attributes.TryGetValue("Width", out strMaxWidth))
{
ulong.TryParse(strMaxWidth, out ulMaxWidth);
}
if (track.Attributes.TryGetValue("MaxHeight", out strMaxHeight) ||
track.Attributes.TryGetValue("Height", out strMaxHeight))
{
ulong.TryParse(strMaxHeight, out ulMaxHeight);
}
if (ulMaxWidth != lastWidth ||
ulMaxHeight != lastHeight)
{
// Current band is now finished, check if it is the widest.
// If same size, current band preferred over previous
// widest, because it will be of higher bitrate.
if (currentBand.Count >= widestBand.Count)
{
// A new widest band:
widestBand = currentBand;
currentBand = new List<TrackInfo>();
}
}
if (track.Bitrate > maxMobileBitrate)
{
break;
}
// Current track always gets added to current band.
currentBand.Add(track);
lastWidth = ulMaxWidth;
lastHeight = ulMaxHeight;
}
if (0 == widestBand.Count &&
0 == currentBand.Count)
{
// Lowest bitrate band is > maxMobileBitrate.
widestBand.Add(streamInfo.AvailableTracks[0]);
}
else if (currentBand.Count >= widestBand.Count)
{
// Need to check the last band which was constructed.
Debug.Assert(currentBand.Count > 0);
widestBand = currentBand; // Winner by default.
}
Debug.Assert(widestBand.Count >= 1);
streamInfo.RestrictTracks(widestBand);
}
}
}
}
void video_PlaybackTrackChanged(object sender, Microsoft.Web.Media.SmoothStreaming.TrackChangedEventArgs e)
{
currentBitrate.Text = e.NewTrack.Bitrate.ToString();
}
void video_CurrentStateChanged(object sender, RoutedEventArgs e)
{
status.Text = video.CurrentState.ToString();
}
private void imghdrleft_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
NavigationService.GoBack();
}
private void imghdrright_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
NavigationService.Navigate(new Uri("/Planet41VIew/Settings.xaml", UriKind.RelativeOrAbsolute));
}
}

Related

Display images in observable collection one after the other as user scrolls in windows phone 8

I have a json array of image URLs added into an observable collection and I want to display the first image on the page such that when a user scrolls horizontally, next or previous images in the array shall display on the screen. Help me achieve this.
Here's how I download the image URLs via json and add them to the observable collection
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<readPageModel> readPages = new ObservableCollection<readPageModel>();
public ObservableCollection<readPageModel> Read_Pages
{
get
{
return readPages;
}
set
{
readPages = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Read_Pages"));
}
}
}
public void DownloadData()
{
WebClient client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri("http://########/mob/ranges/id/3/limit/10/offset/0/r_id/6", UriKind.Absolute));
}
private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
if (!string.IsNullOrEmpty(e.Result))
{
string data = e.Result;
var items = JsonConvert.DeserializeObject<readModel[]>(data);
foreach (var x in items)
{
Read_Pages.Add(x);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You can take scrollviwer in the xaml after this within this scrollviewer take stack panel with horizontal orientation. and then from c# code add image control to this stack panel.
You can have one image control in content panel and implement below code :
public Page()
{
InitializeComponent();
GestureListener gestureListener = GestureService.GetGestureListener(ContentPanel);
gestureListener.DragCompleted += gestureListener_DragCompleted;
//set the initial image to Image control
}
void gestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
{
// User flicked towards left
if (e.HorizontalVelocity < 0)
{
// Load the next image if Downloaded
}
// User flicked towards right
if (e.HorizontalVelocity > 0)
{
// Load the previous image
}
}
you would also needed to have one variable for tracking the index of image to be loaded

How to Keep Toggle Button state in Windows phone 8 application?

I create a toggle button and its working fine . But problem is that how can i Keep previous toggle activity, I mean when application is exit and reopen, it should display the previous toggle state . Here is my code
XAML:
<toolkit:ToggleSwitch x:Name="toggle" Content="ToggleSwitch is on" Header="ToggleSwitch"/>
CS :
public partial class EnglishSub : PhoneApplicationPage
{
public BanglaSub()
{
InitializeComponent();
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
this.toggle.Content = "ToggleSwitch is off";
}
void toggle_Unchecked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "ToggleSwitch is off";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
MessageBox.Show("Disable");
}
void toggle_Checked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "ToggleSwitch is on";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
MessageBox.Show("Enable");
}
}
You can use IsolatedStorageSetings to store application data. and read it when your app page is loaded again. here is how
public bool GetToggleValue()
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("toggleValue"))
{
return bool.Parse(IsolatedStorageSettings.ApplicationSettings["toggleValue"].ToString());
}
else return false;
}
call above method in your page load to set the toggle value
and set checked unchecked value in the settings in your checked unchecked event handlers here is how
IsolatedStorageSettings.ApplicationSettings.Add("toggleValue", true);
IsolatedStorageSettings.Save();

Navigate to the same View. Why Loaded and OnNavigatedTo events aren't called?

Im doing a cloud App(like Skydrive) in Windows Phone 8 , each time I navigate to a different folder I need to reload the FolderView.xaml page to display the content of this folder and I need to add the view to the back stack then I will be able to back to the previous path...
From now when I try to reload the FolderView from the FolderView.xaml.cs page, none event is called...
I don't understand why ? And if you have a solution you are welcome ...
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
if (App.ElementSelected != null)
{
BdeskElement FolderChoosen = new BdeskElement();
FolderChoosen = App.ElementSelected;
Gridentete.DataContext = FolderChoosen;
GetFiles(FolderChoosen);
}
}
private async void llsElements_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LongListSelector llselement = null;
listElementCollection.Clear();
if (sender != null)
llselement =(LongListSelector)sender;
if(llselement.SelectedItem!=null)
{
BdeskElement bdelement=(BdeskElement)llselement.SelectedItem;
if (bdelement.TypeElement==BdeskElement.BdeskTypeElement.Folder)
{
App.DocLibSelected = null;
App.ElementSelected = bdelement;
// I navigate to the same view here but nothing happens
NavigationService.Navigate(new Uri("/Views/BDocs/FolderView.xaml", UriKind.RelativeOrAbsolute));
}
}
}
To navigate to the same page with a new instance, you must change the Uri. For example:
NavigationService.Navigate(new Uri(String.Format("/Views/BDocs/FolderView.xaml?id={0}", Guid.NewGuid().ToString()), UriKind.Relative));
You can discard that parameter if you don't want/use it.

NotSupportedException in Camera App in Windows Phone 8

I am working on Windows Phone 8,since I am new on this technology, I need a help regarding camera. I am working on camera test, I got a NotSupportedException (Specified Method not Supported) kind of exception on back key press event. If I pressed back key immediately after initialization of camera then it will crash the application. I didn't get any source related with this issue.
so, can anyone help me to figure out this problem ?
Thanks
Xaml for your page, might be like this
<Canvas.Background>
<VideoBrush x:Name="viewfinderBrush">
<VideoBrush.RelativeTransform>
<CompositeTransform x:Name="viewfinderBrushTransform" CenterX=".5" CenterY=".5" Rotation="90" />
</VideoBrush.RelativeTransform>
</VideoBrush>
</Canvas.Background>
<StackPanel Name="stkLoading" Height="50" Canvas.Top="245" Visibility="Collapsed">
<TextBlock Foreground="Red" Text="Scanning.." HorizontalAlignment="Center"/>
<ProgressBar IsIndeterminate="True" Width="480"/>
</StackPanel>
</Canvas>
Cs Code
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
base.OnBackKeyPress(e);
//make some navigation like this
NavigationService.Navigate(new Uri("/View/EditDocument.xaml, UriKind.RelativeOrAbsolute));
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
try
{
InitializeCamera();
}
catch (Exception ex)
{
MessageBox.Show("Problem occured in camera declaration.");
}
}
public void InitializeCamera()
{
try
{
if (myCamera != null)
{
myCamera.AutoFocusCompleted -= OnCameraAutoFocusCompleted;
myCamera.Initialized -= myCamera_Initialized;
myCamera.CaptureCompleted -= new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
myCamera.CaptureImageAvailable -= new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(camera_CaptureImageAvailable);
}
viewfinderBrush = null;
canvasCameraView.Background = null;
myCamera = null;
bdrInitializingCamera.Visibility = Visibility.Visible;
viewfinderBrush = new VideoBrush();
CompositeTransform ct = new CompositeTransform();
ct.CenterX = .5;
ct.CenterY = .5;
ct.Rotation = 90;
viewfinderBrush.RelativeTransform = ct;
canvasCameraView.Background = viewfinderBrush;
myCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
viewfinderBrush.SetSource(myCamera);
myCamera.Initialized += myCamera_Initialized;
myCamera.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
myCamera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(camera_CaptureImageAvailable);
}
catch (Exception ex)
{
if (MessageBox.Show("An error occured in camera initialization, please try again. note \n " + ex.Message) == MessageBoxResult.OK)
{
//Make a navigation
}
}
}

WP8 MediaLibrary, view photo in LongListMultiSelector

I need to show all photo present in a my device (WP8) in a LongListMultiSelector.
i use this method
MediaPlayer.Queue.ToString();
MediaLibrary mediaLibrary;
PictureAlbum cameraRoll = null;
foreach (MediaSource source in MediaSource.GetAvailableMediaSources())
{
if (source.MediaSourceType == MediaSourceType.LocalDevice)
{
mediaLibrary = new MediaLibrary(source);
PictureAlbumCollection allAlbums = mediaLibrary.RootPictureAlbum.Albums;
foreach (PictureAlbum album in allAlbums)
{
if (album.Name == "Camera Roll")
{
cameraRoll = album;
}
}
}
}
List<BitmapImage> lstBitmapImage = new List<BitmapImage>();
foreach (Picture p in cameraRoll.Pictures)
{
BitmapImage b = new BitmapImage();
b.SetSource(p.GetThumbnail());
lstBitmapImage.Add(b);
}
PhotoHubLLS.ItemsSource = lstBitmapImage;
In a XAML i have this image setting
<Image HorizontalAlignment="Left" Margin="6,6,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Source="{Binding}"/>
It all works perfectly, but I have some questions.
I would like to Zoom on single picture, on image tap i'm insert this code
FrameworkElement fe = sender as FrameworkElement;
if (fe != null)
{
CurrentPicture = fe.DataContext as Picture;
}
but is null a datacontext because I used "Source".
how can I do?
It depends on which event you've wired up. If you're handling the SelectionChanged event, you can retrieve the BitmapImage (not Picture) from the AddedItems collection in the SelectionChangedEventArgs event arguments parameter:
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
BitmapImage bmp = e.AddedItems[0] as BitmapImage;
}
}
Alternatively if you're handling the Tap event of the Image element in the LongListSelector's ItemTemplate, then you can retrieve the BitmapImage from the sender parameter:
Image imgElement = sender as Image;
BitmapImage bmp = imgElement.Source as BitmapImage;