Access camera preview-stream on Windows Phone 8.1 - c#

I'm trying to create a basic camera application (for my first application targeted towards WP). And I want to, of course, preview the camera data to the screen before taking a shot.
But the only samples I see online from MSDN etc are too old (many objects have been removed, ie the libraries are being updated frequently making the articles obsolete)
I'm having a problem just getting started with the preview-stream. It would be greatly appreciated if someone with knowledge could give me some help in this matter.
Thank you.

I suggest using the CaptureElement control
On your XAML add this:
<CaptureElement x:Name="Capture"
Stretch="UniformToFill"
FlowDirection="LeftToRight" />
I don't know if you want to use front or back webcam so I'll show code for both.
In your codeBehind (or your ViewModel if your using MVVM) add this code:
// First need to find all webcams
DeviceInformationCollection webcamList = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture)
// Then I do a query to find the front webcam
DeviceInformation frontWebcam = (from webcam in webcamList
where webcam.EnclosureLocation != null
&& webcam.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front
select webcam).FirstOrDefault();
// Same for the back webcam
DeviceInformation backWebcam = (from webcam in webcamList
where webcam.EnclosureLocation != null
&& webcam.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
select webcam).FirstOrDefault();
// Then you need to initialize your MediaCapture
var newCapture = new MediaCapture();
await newCapture.InitializeAsync(new MediaCaptureInitializationSettings
{
// Choose the webcam you want (backWebcam or frontWebcam)
VideoDeviceId = backWebcam.Id,
AudioDeviceId = "",
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview
});
// Set the source of the CaptureElement to your MediaCapture
Capture.Source = newCapture;
// Start the preview
await newCapture.StartPreviewAsync();
This will show the stream of the chosen webcam in your CaptureElement control, and works on both Windows Phone 8.1 and Windows 8.1

Related

How to use ZXing Barcode Scanner in a Xamarin Forms app?

I'm trying to figure out how use to use ZXing Barcode Scanner nuget package in a simple Xamarin Forms application.
I'm trying to have a large area of my form show what my camera is seeing .. and if it scan's something.. then stop scanning and goto the next Page.
All the examples basically show this:
buttonScan.Click += (sender, e) => {
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
var result = await scanner.Scan();
if (result != null)
Console.WriteLine("Scanned Barcode: " + result.Text);
};
but I don't understand what the actual view/control/widget which gets displayed onto the actual page, is? Like a big square with the camera contents getting displayed etc.
What is the trick to drop a control onto the page .. which I can then wire up to scan whatever the camera is 'seeing' .. and hopefully it will 'read' the barcode or qrcode?

Simultaneous microphone recording and audio playback (WP 8.1 XAML)

Using the MediaElement control and MediaCapture class, I am trying to record microphone input and play audio at the same time.
As soon as I start recording, whatever track is playing mutes. I don't think it stops, because it continues playing after the recording has stopped. I have added hooks into several events on the MediaElement and none are being fired. For example, CurrentStateChanged, MediaEnded, MediaFailed etc.
Recording code:
public async void InitializeMediaCapture()
{
_mediaCaptureManager = new MediaCapture();
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
settings.MediaCategory = MediaCategory.Other;
await _mediaCaptureManager.InitializeAsync(settings);
}
private async void CaptureAudio()
{
_recordStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
var recordProfile = MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Auto);
await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, this._recordStorageFile);
//audio playback stops on preceding line of code
}
I use .Play() on the MediaElement to play the audio, with the control in my XAML and the audio source set there.
<MediaElement x:Name="playbackElement"
Source="ms-appx:///Audio/Song.mp3"
AutoPlay="False" />
I have also tried playing the audio as BackgroundAudio, but that didn't work either. Any ideas?
1.Never set a MediaElement's Source in XAML, unless that XAML is on a page that you navigate to after asking the user for consent.
2.Check to see if background music is playing and then set the source (in code).
Note: If you set the source and then immediately call Play(), the Play() will have no affect since the MediaElement will still be in the "Opening" state, instead set "AutoPlay = true" (works from code)
Here's a Reference

WP7 how to get current song

I have a track which is playing on my phone and then I pause it using the controls that pop down after pressing the volume keys.
In my application, how can I resume that song and find out what the song is?
The following does not work.
MediaPlayer.Queue.ActiveSong // This reports no songs at all. Only works if I give it a song to play
MediaHistory.Instance.NowPlaying.Title // MediaHistory.Instance = null
Also just trying this does nothing.
MediaPlayer.Resume
Edit: If it makes any difference, I am debugging a Windows Phone 7 app on and Windows Phone 8 device.
If I give a song to MediaPlayer to play then all the above works.
to play a song
MediaPlayer.Play(SongCollection songs);
MediaPlayer.Play(SongCollection songs,int index);
and to get songs
MediaLibrary mLibrary = new MediaLibrary();
songs = mLibrary.Songs;
to check current state
if(MediaPlayer.State == MediaState.Playing || MediaPlayer.State == MediaState.Paused)
and to check active song
Microsoft.Xna.Framework.Media.MediaPlayer.Queue.ActiveSong.Name;

Launching Webcam in Metro style apps

I am building a win8 app which requires to launch the webcam for taking photos only.
I have seen the sample codes given in MSDN for Camera captures but I only want is onclick of CAPTURE Button the webcam should launched, take a pic and save it.
While in the sample codes they made the user to select option from the list box and on selectionchanged, the required function has been called. My problem is that I don't required any Listbox. Also they have used a class called SuspensionManager which I didn't understand. I am really confused.
Can somebody show me a way out?
Try this:
using Windows.Media.Capture;
var ui = new CameraCaptureUI();
ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
var bitmap = new BitmapImage();
bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
Photo.Source = bitmap;
}
Took from here

Silverlight media player

I am using VSTS 2008 with C# to develop Silverlight application embedded in web page of an ASP.Net web application. I have embedded in XAML a MediaElement item. My question is, I want to embed the page a Silverlight media player, which could let end user to control the MediaElement item manually to -- play/pause/stop/rewind/forward. Are there any references samples?
thanks in advance,
George
EDIT1: add more accurate requirements,
Actually, I want to control play manually, which means I want to handle the player play/pause/stop/rewind/forward events and add my code for the event handlers to control the MediaElement and do something else.
EDIT2: My needs are, I want to play two overlapped video. Screen as background video and camera as foreground video (place at right bottom corner). Here is my modification of code, my current issue is, only background video is played, foreground right bottom video is never played. Does anyone have any ideas why?
BTW: my modified code and current work is based on http://www.codeplex.com/sl2videoplayer
http://www.yourfilehost.com/media.php?cat=other&file=sl2videoplayer_24325_new.zip
Here is a brief description of my major modified code,
mediaControls.xaml.cs
private MediaElement _media = null;
private MediaElement _camera = null;
public MediaElement Camera
{
set
{
_camera = value;
}
}
void btnPlay_Checked(object sender, RoutedEventArgs e)
{
_camera.Play();
_media.Play();
OnPlayClicked();
}
Page.xaml
<MediaElement HorizontalAlignment="Stretch" Margin="0,0,0,0" x:Name="mediaPlayer" Stretch="Uniform" VerticalAlignment="Stretch" AutoPlay="false"/>
<MediaElement Width="100" Height="100" x:Name="cameraPlayer" AutoPlay="false" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
Page.xaml.cs
cameraPlayer.Source = App.Current.Resources["c"] as Uri;
App.xaml.cs (Application_Startup function)
else if (item.Key.ToLower() == "c")
{
FormatUri(e.InitParams["c"].ToString(), "c", false);
}
default.html
<param name="initParams" value="cc=true,markers=true,markerpath=markers_movie21.xml,m=http://localhost/screen.wmv,c=http://localhost/camera.wmv" />
Oh baby have I got the media player for you: Sl2 Video Player. MSPL open sourced and awesome.
To add the ability to control the player pragmatically, add ScriptableMembers.
You'll see the registration statement already in the code:
HtmlPage.RegisterScriptableObject("Page", page);
Now look at an example ScriptableMember:
[ScriptableMember]
public void SeekPlayback(string time)
{
TimeSpan tsTime = TimeSpan.Parse(time);
mediaControls.Seek(tsTime);
}
already exists in the code. Add more methods to do what you want to have happen. Then you can call the methods from managed code in another SL player:
HtmlElement videoPlugin = HtmlPage.Document.GetElementById("VideoPlayer");
if (videoPlugin != null)
{
ScriptObject mediaPlayer = (ScriptObject)((ScriptObject)videoPlugin.GetProperty("Content")).GetProperty("Page");
mediaPlayer.Invoke("SeekPlayback", TimeSpan.FromSeconds(seconds).ToString());
}
or from javascript:
var sl = document.getElementById("VideoPlayer");
var content = sl.Content.Page;
content.SeekPlayback('55');
If they are two seperate xap packages, there will be no way for the two to communicate since Silverlight sandboxes both individually.
SL2videoplayer says it supports streaming video. But when I try giving a media services broadcast url (OnDemand and Live) to init param 'm' nothing showed up. In the init param example page also a remote wmv file being played is shown.
Also are there any known issues of using this with SL 3?

Categories

Resources