WindowsPhone 8.1 FlashLight - c#

I have Nokia 730 and I want to make FlashLight work on it. But next code crash:
MediaCapture mc = new MediaCapture();
await mc.InitializeAsync();
if (mc.VideoDeviceController.TorchControl.Supported == true)
{
mc.VideoDeviceController.TorchControl.Enabled = true;
mc.VideoDeviceController.TorchControl.PowerPercent = 100; // here is crash
}
Any ideas? For some reasons solutions with older platforms (wp 7, wp8) doesn't works at all.

Fixed it by next code:
private async void Button_Click(object sender, RoutedEventArgs e)
{
// Initialize Media Capture and Settings Objects, mediaCapture declared global outside this method
var mediaCapture = new MediaCapture();
// Grab all available VideoCapture Devices and find rear device (usually has flash)
await mediaCapture.InitializeAsync();
var videoEncodingProperties = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga);
var videoStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync("tempVideo.mp4", CreationCollisionOption.GenerateUniqueName);
await mediaCapture.StartRecordToStorageFileAsync(videoEncodingProperties, videoStorageFile);
await Task.Delay(TimeSpan.FromMilliseconds(500));
mediaCapture.VideoDeviceController.TorchControl.Enabled = true;
}
But for some reason I should wait 500 milliseconds before enable TorchControl. Can someone explain why?

According to this post it could help to try the following:
//to switch OFF flash light
mc.VideoDeviceController.FlashControl.Enabled = false;
//to switch ON flash light
mc.VideoDeviceController.FlashControl.Enabled = true;

Related

UWP AutoNext Function

I'm trying to Get a Auto Next method i've tried using a Index Counter but I think I misunderstand how to properly set a list using the FilePicker
The code for the FilePicker is following :
public async void pick_Click_1(object sender, RoutedEventArgs e)
{
List<StorageFile> fileList = new List<StorageFile>();
var fop = new FileOpenPicker();
fop.FileTypeFilter.Add(".mp3");
fop.FileTypeFilter.Add(".mp4");
fop.FileTypeFilter.Add(".avi");
fop.FileTypeFilter.Add(".wmv");
fop.ViewMode = PickerViewMode.List;
pickedFileList = await fop.PickMultipleFilesAsync();
// add the picked files to our existing list
fileList.AddRange(pickedFileList);
foreach (StorageFile file in pickedFileList)
{
Playlist.Items.Add(file);
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
videoMediaElement.SetSource(stream, file.ContentType);
}
videoMediaElement.Play();
The Current method i have for switching tracks|Videos
private async void itemclicked(object sender, ItemClickEventArgs e)
{
var file = e.ClickedItem as StorageFile;
if (file != null)
{
var stream = await file.OpenReadAsync();
videoMediaElement.SetSource(stream, file.ContentType);
}
}
Empty Event im trying to use to do this.
private void Element_MediaEnded(object sender, RoutedEventArgs e)
{
}
I've looked threw all the Microsoft Sample's. Issue Being They use the Mediaplayerelement += Mediaplayer And im using the MediaElement
The Answers Im looking for Can be A Resolution to my problem or assisting me in better understanding how to globally set the source of the mediaplayer using the Current or new list from the picker, Im new to all this and trying to grasp everything better Thank you!
I ended up taking Tousee's advice to seem's he's my mentor at this stage, I used the MediaplayerElement and mediaPLaybacklist's which made life Easier. And almost instantly fixed my problem.

MediaElement is refusing to loop

So I was trying to loop Background music in my UWP App, I have a class called soundControl that handles music and sounds like this:
public class soundControl
{
private static MediaElement loop = new MediaElement();
public static async void stopLoop()
{
loop.Stop();
}
public static async void loadLoopTimeBG()
{
Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(#"Assets\Sounds");
Windows.Storage.StorageFile file = await folder.GetFileAsync("battle.wav");
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
loop.AutoPlay = false;
loop.SetSource(stream, file.ContentType);
loop.IsLooping = true;
}
public static void loopTimeBG()
{
loop.Play();
}
And whenever I want to play this music I call :
soundControl.loadLoopTimeBG();
soundControl.loopTimeBG();
the problem is the it plays just one time and stops and I have no Idea why
I tried another approach like:
loop.MediaEnded += mediaEnded;
and the event handler like this:
private static void mediaEnded(object sender, RoutedEventArgs e)
{
loop.Position = TimeSpan.Zero;
loop.Play();
}
it also didn't work and when debugging it doesn't even triger the mediaEnded event when music is complete.
Any help here would be most appreciated.
Thanks
MediaPlayer
Windows.Media.Playback.MediaPlayer is the recommended player for UWP that does not require to be in the XAML visual tree.
Its API is very similar to MediaElement:
private static MediaPlayer _mediaPlayer = new MediaPlayer();
public static async Task PlayUsingMediaPlayerAsync()
{
Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(#"Assets");
Windows.Storage.StorageFile file = await folder.GetFileAsync("Click.wav");
_mediaPlayer.AutoPlay = false;
_mediaPlayer.Source = MediaSource.CreateFromStorageFile(file);
_mediaPlayer.MediaOpened += _mediaPlayer_MediaOpened;
_mediaPlayer.IsLoopingEnabled = true;
}
private static void _mediaPlayer_MediaOpened(MediaPlayer sender, object args)
{
sender.Play();
}
You can even display the visuals of a MediaPlayer in XAML using MediaPlayerElement.
MediaPlayer allows for even more advanced playback scenarios using the MediaPlaybackList with support for looping, shuffle and gapless playback.
mediaElement.SetPlaybackSource(mediaPlaybackList);
MediaElement
After some digging around it seems that there are two issues.
MediaElement is XAML based control (in the Windows.UI.Xaml.Controls namespace), and it seems that it does not work properly until it is actually attached to a visual tree. Once you put the MediaElement on the page, it works as expected.
Secondly, loading source media does not happen immediately. Once you set the source, the control needs some time to actually load the media. For this purpose, you can use the MediaOpened event, that will notify you once it is really loaded.
So the code could look somewhat like this:
public static async Task LoadAndPlayAsync()
{
Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(#"Assets");
Windows.Storage.StorageFile file = await folder.GetFileAsync("Click.wav");
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
loop.AutoPlay = false;
loop.SetSource(stream, file.ContentType);
//or simpler -
//loop.Source = new Uri("ms-appx:///Assets/Click.wav", UriKind.Absolute);
loop.MediaOpened += Loop_MediaOpened;
loop.IsLooping = true;
}
private static void Loop_MediaOpened(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
//play once the media is actually ready
loop.Play();
}
And before you call the LoadAndPlayAsync method, you have to attach the control somewhere (for example in a Grid):
GridContainer.Children.Add(SoundController.loop);
await SoundController.LoadAndPlayAsync();
I have created a sample project for my tests on my GitHub, you can check it out to see how I implemented it. The first button in the app attaches the control and the second loads and plays the sound. You can see that if you click only the second one, the sound does not play.

Image sending app for Windows Phone

I'm developing app for Windows Phone 8.1 which have :
Page with file open picker to take photo from gallery and second Page
to sending that one photo as an e-mail attachment with message.
How i can take this one picked picture and send this with e-mail.?
I tried to look some solutions but so far without any luck.
Any suggestion please?
The code is in regular c# and xaml and I'm using Windows Phone 8.1 in Visual Studio 2015.
You can use this solution to your problem in a single step.
/// <summary>
/// Taking photo from the gallery
/// </summary>
private void SharePhotoClick(object sender, RoutedEventArgs e)
{
PhotoChooserTask ph=new PhotoChooserTask();
ph.Completed += ph_Completed;
ph.Show();
}
/// <summary>
/// Sharing the photo to social media including email
/// </summary>
void ph_Completed(object sender, PhotoResult e)
{
ShareMediaTask smt = new ShareMediaTask();
smt.FilePath = e.OriginalFileName;
smt.Show();
}
Hope this helps!
Note: Please ignore or remove answer if you are developing universal wp application.
I believe in WP8.1 you would require to implement the IContinuationManager which will help you get the image selected by the user.
First you need an event where you open up the Gallery
private void PickAFileButton_Click(object sender, RoutedEventArgs e)
{
...
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
// Launch file open picker and caller app is suspended
// and may be terminated if required
openPicker.PickSingleFileAndContinue();
}
Once the image is selected then OnActivated() method in app.xaml.cs is called where you need continuation manager to get the data of file selected.
protected async override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args);
var continuationManager = new ContinuationManager();
var rootFrame = CreateRootFrame();
await RestoreStatusAsync(args.PreviousExecutionState);
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MainPage));
}
var continuationEventArgs = e as IContinuationActivatedEventArgs;
if (continuationEventArgs != null)
{
Frame scenarioFrame = MainPage.Current.FindName("ScenarioFrame") as Frame;
if (scenarioFrame != null)
{
// Call ContinuationManager to handle continuation activation
continuationManager.Continue(continuationEventArgs, scenarioFrame);
}
}
Window.Current.Activate();
}
Now the continuation manager will handle the activation for you.
case ActivationKind.PickSaveFileContinuation:
var fileSavePickerPage = rootFrame.Content as IFileSavePickerContinuable;
if (fileSavePickerPage != null)
{
fileSavePickerPage.ContinueFileSavePicker(args as FileSavePickerContinuationEventArgs);
}
break;
case ActivationKind.PickFolderContinuation:
var folderPickerPage = rootFrame.Content as IFolderPickerContinuable;
if (folderPickerPage != null)
{
folderPickerPage.ContinueFolderPicker(args as FolderPickerContinuationEventArgs);
}
break;
case ActivationKind.WebAuthenticationBrokerContinuation:
var wabPage = rootFrame.Content as IWebAuthenticationContinuable;
if (wabPage != null)
{
wabPage.ContinueWebAuthentication(args as WebAuthenticationBrokerContinuationEventArgs);
}
break;
}
All the code snippets are available here https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx
Once this is done you can fetch the data and save it to a file and attach that file to email.
EmailMessage email = new EmailMessage();
email.To.Add(new EmailRecipient("test#abc.com"));
email.Subject = "Test";
var file = await GetFile();
email.Attachments.Add(new EmailAttachment(file.Name, file));
await EmailManager.ShowComposeNewEmailAsync(email);
More details in this link http://developerpublish.com/windows-phone-8-1-and-windows-runtime-apps-how-to-2-send-emails-with-attachment-in-wp-8-1/
Hope this helps!

voice command to capture photo

I use Windows.Media.Capture.MediaCapture in my Windows Phone 8.1 app to capture a photo. Instead of a button, I'd like to trigger the photo capturing process by a voice command (for example, if the user says 'cheese'). How can I detect such a voice command?
You can use the SpeechRecognizer class.
Here's a sample from MSDN:
private async void StartRecognizing_Click(object sender, RoutedEventArgs e)
{
// Create an instance of SpeechRecognizer.
var speechRecognizer = new Windows.Media.SpeechRecognition.SpeechRecognizer();
// Compile the dictation grammar by default.
await speechRecognizer.CompileConstraintsAsync();
// Start recognition.
Windows.Media.SpeechRecognition.SpeechRecognitionResult speechRecognitionResult = await speechRecognizer.RecognizeWithUIAsync();
// Do something with the recognition result.
var messageDialog = new Windows.UI.Popups.MessageDialog(speechRecognitionResult.Text, "Text spoken");
await messageDialog.ShowAsync();
}

How get navigation control from a button?

I know if I used a view controller I can use this:
var scanner = new MobileBarcodeScanner(this.NavigationController);
How do I know what navigation I am using inside of button I need use?
public class BarReaderButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
// I tried this but don't worked
var scanner = new MobileBarcodeScanner(this.NavigationController);
// I tried this but do
var scanner = new MobileBarcodeScanner(this);
Element.Clicked += async(s_, e_) => {
// Setup our button
// Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of the default overlay
scanner.TopText = "Hold camera up to barcode to scan";
scanner.BottomText = "Barcode will automatically scan";
//Start scanning
var result = await scanner.Scan ();
HandleScanResult(result);
};
}
}
I can't use this code inside a button render. Or did someone this before?
The project is a shared application for iOS and Android.
The code for creating the scanner should stay inside the view controller/activity/page. You can still use the custom button and add the code you need to the Clicked event handler.
var myCustomButton = new BarReaderButton();
myCustomButton.Clicked += async(s, e) => {
var scanner = new MobileBarcodeScanner();
scanner.UseCustomOverlay = false;
//Start scanning
var result = await scanner.Scan ();
//Do something with the result
};
If this is Xamarin.Forms you will also have to use platform specific code inside the Page code as the barcode reader requires a Context on Android:
#if __IOS__
var scanner = new MobileBarcodeScanner();
#elif __ANDROID__
var scanner = new MobileBarcodeScanner(Forms.Context);
#endif

Categories

Resources