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
}
}
}
Related
I want to implement the "toast" notification inside my windows phone application. I'm implementing push message's, but I want them to show always. No matter if the application is running or not. The push notification will handle it when the application is closed, but not when it is running. Also if I create a shelltoast manually it won't show. To make it more difficult I can't use any external dll's. I only want to use code. What would be the best way to do this? I already know about the ToastNotificationRecieved event. I want to know how to implement it so that it will show a "toast" like message without using a framework
My code is below
PushPlugin.cs(c# code)
public void showToastNotification(string options)
{
ShellToast toast;
if (!TryDeserializeOptions(options, out toast))
{
this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
Deployment.Current.Dispatcher.BeginInvoke(toast.Show);
}
public void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
var toast = new PushNotification
{
Type = "toast"
};
foreach (var item in e.Collection)
{
toast.JsonContent.Add(item.Key, item.Value);
}
this.ExecuteCallback(this.pushOptions.NotificationCallback, JsonConvert.SerializeObject(toast));
}
In javascript
function onNotificationWP8(data) {
var pushNotification;
pushNotification = window.plugins.pushNotification;
pushNotification.showToastNotification(successHandler, errorHandler,
{
"Title": data.jsonContent["wp:Text1"], "Content": data.jsonContent["wp:Text2"], "NavigationUri": data.jsonContent["wp:Param"]
});
}
On devices without Windows Phone 8 Update 3, toast notifications are not displayed when the target app is running in the foreground. On devices with Windows Phone 8 Update 3, toast notifications are displayed when the target app is running in the foreground, but is obscured by other activity such as a phone call or the lock screen.
The following C# code example shows the properties used to create a toast notification using local code.
// Create a toast notification.
// The toast notification will not be shown if the foreground app is running.
ShellToast toast = new ShellToast();
toast.Title = "[title]";
toast.Content = "[content]";
toast.Show();
This thread has it all you looking for
public static class Notification
{
public static string ChannelURI = string.Empty;
public static void MainNotificationCallFunction()
{
try
{
NotificationMessage("Test Notification");
}
catch (Exception e)
{ }
}
public static void NotificationMessage(string Message)
{
try
{
ToastTemplateType toastType = ToastTemplateType.ToastText02;
XmlDocument toastXmlJob = ToastNotificationManager.GetTemplateContent(toastType);
XmlNodeList toastTextElementJob = toastXmlJob.GetElementsByTagName("text");
toastTextElementJob[0].AppendChild(toastXmlJob.CreateTextNode(Message));
IXmlNode toastNodeJob = toastXmlJob.SelectSingleNode("/toast");
((XmlElement)toastNodeJob).SetAttribute("duration", "long");
ToastNotification toastJob = new ToastNotification(toastXmlJob);
ToastNotificationManager.CreateToastNotifier().Show(toastJob);
}
catch (Exception e)
{ }
}
public static void PushNotification()
{
try
{
/// Holds the push channel that is created or found.
HttpNotificationChannel pushChannel;
string channelName = "Usman's Channel";
// Try to find the push channel.
pushChannel = HttpNotificationChannel.Find(channelName);
// If the channel was not found, then create a new connection to the push service.
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
//// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
pushChannel.Open();
pushChannel.BindToShellTile();
pushChannel.BindToShellToast();
}
else
{
//// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
}
}
catch (Exception ex)
{ }
}
private static void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
MessageBox.Show(String.Format("Channel Uri is {0}", e.ChannelUri.ToString()));
});
}
catch (Exception ex)
{ }
}
private static void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
try
{
// Error handling logic for your particular application would be here.
Deployment.Current.Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData)));
}
catch (Exception ex)
{ }
}
private static void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
try
{
string message;
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(String.Format("Received Notification {0}:\n{1}", DateTime.Now.ToShortTimeString(), message)));
}
catch (Exception ex)
{ }
}
private static void channel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(e.Message, "Error", MessageBoxButton.OK);
});
}
catch (Exception ex)
{ }
}
private static void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//ProgressBarPushNotifications.Visibility = System.Windows.Visibility.Collapsed;
MessageBox.Show(e.ChannelUri.ToString(), "Uri Recieved", MessageBoxButton.OK);
});
}
catch (Exception ex)
{ }
}
private static void channel_ShellToastNotificationReceived(object sender, HttpNotificationEventArgs e)
{
try
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message.AppendFormat(reader.ReadToEnd());
}
// Display a dialog of all the fields in the toast.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(message.ToString());
});
}
catch (Exception ex)
{ }
}
}
If I have an element like this in a Windows Store or Windows Phone application:
<Image Source="{Binding UrlToWebServer}" />
the image is cached locally. This is great. But how do I remove all cached images on disc from code?
You just have to set the imagesource to NULL
Something like this:
BitmapImage bitmapImage = myimage.Source as BitmapImage;
bitmapImage.UriSource = null;
myimage.Source = null;
This works for me. Here you can find mor infos handling images (section Image Caching for example).
Hi it´s a little bit late to answer this question but you can use this class to delete the cache of a specific files or all if you want
this is the class helper
class CacheCleanup : IDisposable
{
private DispatcherTimer cleanCacheTimer;
public CacheCleanup(TimeSpan? cleanInterval = null)
{
if (!cleanInterval.HasValue)
cleanInterval = TimeSpan.FromMinutes(0.2);
cleanCacheTimer = new DispatcherTimer();
cleanCacheTimer.Interval = cleanInterval.Value;
cleanCacheTimer.Tick += CleanCacheTimer_Tick;
cleanCacheTimer.Start();
}
private void CleanCacheTimer_Tick(object sender, object e)
{
try
{
StorageFolder localDirectory = ApplicationData.Current.LocalFolder;
string[] tmpCacheDirectories = Directory.GetDirectories(localDirectory.Path + "\\..\\ac\\inetcache");
foreach (string dir in tmpCacheDirectories)
{
string[] tmpCacheFilesPng = Directory.GetFiles(dir, "*.png");
foreach (string file in tmpCacheFilesPng)
{
try
{
File.Delete(file);
Debug.WriteLine("Deleted png: " + file);
}
catch (Exception) { }
}
string[] tmpCacheFilesJpg = Directory.GetFiles(dir, "*.jpg");
foreach (string file in tmpCacheFilesJpg)
{
try
{
File.Delete(file);
Debug.WriteLine("Deleted jpg: " + file);
}
catch (Exception) { }
}
}
}
catch (Exception ex) { Debug.WriteLine("ERROR CLEANING CACHE: " + ex.Message); }
}
public void Dispose()
{
if (cleanCacheTimer != null)
{
cleanCacheTimer.Stop();
cleanCacheTimer = null;
}
}
}
and this is the way how you can call this class in some part of your c# code
CacheCleanup cacheCleanup = new CacheCleanup();
Im working with windows phone 8.1 geolocation. The problem that I currently have is that my code only shows the first numbers of my coordinate. Example: If the coordinate is "41.233" the app only shows "41.00" . I need it to be as accurate as possible. In case it matters, im using windows phone 8.1 emulator to try the app, not an actual phone.
My code:
public sealed partial class MainPage : Page
{
bool shouldSend = false;
DispatcherTimer timer = new DispatcherTimer();
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
private async Task GetLocation()
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.High;
try
{
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromSeconds(1),
timeout: TimeSpan.FromSeconds(10)
);
LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
LatLonTxt.Text = LatitudeTxt.Text + ", " + LongitudeTxt.Text;
var speed = geoposition.Coordinate.Speed.ToString();
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
string result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
"http://proyecto-busways.rhcloud.com/colectivos?p=lta123&l=80&d=moyano&lat=" + LatitudeTxt.Text + "&lon=" + LongitudeTxt.Text + "&v=" + speed + "&Accion=Agregar");
request.ContinueTimeout = 4000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
{
if (response.StatusCode == HttpStatusCode.OK)
{
//To obtain response body
using (Stream streamResponse = response.GetResponseStream())
{
using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8))
{
result = streamRead.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
if ((uint)ex.HResult == 0x80004004)
{
// the application does not have the right capability or the location master switch is off
}
//else
{
// something else happened acquring the location
}
}
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private async void StartSending_Click(object sender, RoutedEventArgs e)
{
await GetLocation();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
StartSending.IsEnabled = false;
}
async void timer_Tick(object sender, object e)
{
ProcessingTxt.Visibility = Windows.UI.Xaml.Visibility.Visible;
await GetLocation();
}
private void EndSending_Click(object sender, RoutedEventArgs e)
{
timer.Tick -= timer_Tick;
timer.Stop();
StartSending.IsEnabled = true;
EndSending.IsEnabled = false;
}
private void GPS_Tapped(object sender, TappedRoutedEventArgs e)
{
Frame.Navigate(typeof(ContactPage));
}
}
Thanks for your help!
Did you try out the Geolocator.DesiredAccuracyInMeters property?
geolocator.DesiredAccuracyInMeters = 3;
Reference & Sample
In this point LatitudeTxt.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTxt.Text = geoposition.Coordinate.Longitude.ToString("0.00");
You indicated that you have 0.00 decimals, for more accuracy you should put 0.000000
I am developing windows phone app .In this app i need to integrate with foursquare,So I loaded the url of foursqare in web browser.Web browser loaded the four square login page upto this it is working fine when i enter the login details and press enter,Then i will hide web browser and show the data in a list which came from service.After 10-15 seconds app gets crashes.This crash will not seen in emulator it happens only in phone(lumia 520).In lumia 920 it works fine
my xaml code
<Grid Grid.ColumnSpan="2" Name="browserGrid" Visibility="Visible">
<phone:WebBrowser x:Name="foursquareBrowser" IsScriptEnabled="True" VerticalAlignment="Top" Height="720" />
<!--<ProgressBar x:Name="progressBar" IsIndeterminate="True" Visibility="Collapsed"/>-->
</Grid>
browser.cs
void foursquareBrowser_Loaded(object sender, RoutedEventArgs e)
{
try
{
foursquareBrowser.Navigate(new Uri("https://foursquare.com/oauth2/authorize?client_id=EYXOAIOMY3BNFR3DPB4SCK1JGR1J3FKDES4O5RGE3DDDM5WI&response_type=code&redirect_uri=http://www.visitabudhabi.ae"));
foursquareBrowser.Navigating+=foursquareBrowser_Navigating;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void foursquareBrowser_Navigating(object sender, NavigatingEventArgs e)
{
try
{
if (e.Uri.OriginalString.Contains("https://foursquare.com/login"))
{
foursquareBrowser.Navigate(new Uri("https://foursquare.com/oauth2/authorize?client_id=EYXOAIOMY3BNFR3DPB4SCK1JGR1J3FKDES4O5RGE3DDDM5WI&response_type=code&redirect_uri=http://www.visitabudhabi.ae"));
}
else if (e.Uri.OriginalString.Contains("code="))
{
uri = e.Uri.OriginalString.ToString().Split(new string[] { "code=" }, StringSplitOptions.None).Last();
uri = uri.Remove(uri.Length - 4);
WebClient wc = new WebClient();
string postData = string.Empty;
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.UploadStringAsync(new Uri("https://foursquare.com/oauth2/access_token?client_id=EYXOAIOMY3BNFR3DPB4SCK1JGR1J3FKDES4O5RGE3DDDM5WI&client_secret=1ROOV3FGYQZMVXV0TB1BRMHRIKB3RHI224M2NV0YFC0XXC1U&grant_type=authorization_code&redirect_uri=http://www.visitabudhabi.ae&code=" + uri, UriKind.Absolute), "POST", postData.ToString());
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc1_UploadStringCompleted);
foursquareBrowser.Navigating-=foursquareBrowser_Navigating;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
It is crashing simply without any debugging information.
Check Syntax at this line
foursquareBrowser.Navigate(new Uri("https://foursquare.com/oauth2/authorize? client_id=EYXOAIOMY3BNFR3DPB4SCK1JGR1J3FKDES4O5RGE3DDDM5WI&response_type=code&redirect_uri=http://www.visitabudhabi.ae"));
It seems to be you missed this from above syntax UriKind.RelativeOrAbsolute
foursquareBrowser.Navigate(new Uri("https://foursquare.com/oauth2/authorize?client_id=EYXOAIOMY3BNFR3DPB4SCK1JGR1J3FKDES4O5RGE3DDDM5WI&response_type=code&redirect_uri=http://www.visitabudhabi.ae",UriKind.RelativeOrAbsolute));
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));
}
}