I left JavaScript and started to work on Windows 8 Metro using C# and XAML, in this post I’ll demonstrate how to use WinRT for Camera, File Picker and Audio Recording.

Download Demo Project
Step 1: Create Blank Metro Project and Initialize MediaCapture
Taking pictures using Camera or File Picker is pretty easy using WinRT, we going to use the MediaCapture class for Audio Recording, CameraCaptureUI for taking Picture from the built in Camera and FileOpenPicker for choosing pictures from local directories.
The MediaCapture class will allow us to capture:
But first we need to create our project resources and define the Application Capabilities to allow us using those features.
Open Package.appmanifest file located under the project and select the following:
Each of the below selections gives the application the needed permissions to work with those features.

MediaCapture mediaCaptureMgr;
StorageFile recordStorageFile;
bool recording;
DeviceInformationCollection devInfoCollection;
public BlankPage()
{
this.InitializeComponent();
mediaCaptureMgr = new MediaCapture();
}
/// <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. The Parameter
/// property is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
EnumerateWebcamsAsync();
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
await mediaCaptureMgr.InitializeAsync(settings);
}
Step 2: EnumerateWebcamsAsync
The code below using DeviceInformation.FindAllAsync method to get all media devices on your machine, you can also use this to get specific devices such as AudioCapture, AudioRender, PortableStorageDevice or VideoCapture.
Then we just add the name of each device found to a listbox.
async void EnumerateWebcamsAsync()
{
try
{
devInfoCollection = null;
EnumedDeviceList.Items.Clear();
devInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.All);
if (devInfoCollection == null || devInfoCollection.Count == 0)
{
await new Windows.UI.Popups.MessageDialog("No WebCams found.").ShowAsync();
}
else
{
for (int i = 0; i < devInfoCollection.Count; i++)
{
var devInfo = devInfoCollection.ElementAt(i);
EnumedDeviceList.Items.Add(devInfo.Name);
}
EnumedDeviceList.SelectedIndex = 0;
}
}
catch (Exception e)
{
new Windows.UI.Popups.MessageDialog(e.Message).ShowAsync();
}
}
Step 3: File Picker
File Picker is part of WinRT, allowing the user to choose files from local directories.
In the code below we define new class of FileOpenPicker and set several options:
- ViewMode - Thumbnail or List
- SuggestedStartLocation – Start Location
- FileTypeFilter – Supported file types
Finally we call the PickMultipleFilesAsync to open the file picker and allowing the user to select multiple images. (You can also use PickSingleFileAsync for single image selection)
When the user click select the desire images and click the OK button we get a IReadOnlyList of StorageFile, in order to show them on the screen we can get the stream from each item our we can copy those file to our local storage and then use the “ms-appdata:///Local/FileName” path to display those images from our local storage folder.
private async void btnFilePicker_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");
IReadOnlyList<StorageFile> files = await openPicker.PickMultipleFilesAsync(); //PickSingleFileAsync
if (files.Count == 0)
{
await new Windows.UI.Popups.MessageDialog("No files were seleced!").ShowAsync();
return;
}
var storage = Windows.Storage.ApplicationData.Current.LocalFolder;
foreach (var file in files)
{
var copiedFile = await file.CopyAsync(storage, file.Name, NameCollisionOption.GenerateUniqueName);
listImages.Items.Add(string.Format("ms-appdata:///Local/{0}", copiedFile.Name));
}
}
Step 4: Camera Capture
Now it’s time to capture a image from the built in Camera, to do so we’ll use the CameraCaptureUI, simply define what type of image you want to receive by defining the Format, size etc..
After the user close the Camera dialog we check if the return file isn’t null and if it doesn't we use OpenAsyc method to get the file stream and then using that stream we’ll create a new BitmapImage from that stream and assign it to the ImgCamera.
private async void btnCamera_Click(object sender, RoutedEventArgs e)
{
try
{
CameraCaptureUI dialog = new CameraCaptureUI();
Size aspectRatio = new Size(16, 9);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
dialog.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Png;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var bmpimg = new BitmapImage();
bmpimg.SetSource(stream);
ImgCamera.Source = bmpimg;
stream.Dispose();
}
}
catch (Exception ex)
{
new Windows.UI.Popups.MessageDialog(ex.Message).ShowAsync();
}
}
Step 5: Audio Recording
No for the last part of application, Recording Audio, first we’ll create a StorageFile inside the Music Library, we’ll set the recording profile to create an M4a file type and just calling the StartRecordToStorageFileAsync method of the MediaCapture class passing the storageFile and the recording profile.
After the user click the stop button we call the StopRecordAsync method, this will stop the recording and same as we did for the Camera, we open the file stream and assign the stream to the MediaPlayer source.
private async void btnAudio_Click(object sender, RoutedEventArgs e)
{
try
{
String fileName = "AudioRecording.m4a";
if (!recording)
{
recordStorageFile = await Windows.Storage.KnownFolders.MusicLibrary.CreateFileAsync(fileName);
Windows.Media.MediaProperties.MediaEncodingProfile recordProfile = null;
recordProfile = Windows.Media.MediaProperties.MediaEncodingProfile.CreateM4a(Windows.Media.MediaProperties.AudioEncodingQuality.Auto);
recording = true;
btnAudio.Content = "Stop Recording";
await mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, recordStorageFile);
}
else
{
await mediaCaptureMgr.StopRecordAsync();
btnAudio.Content = "Start Recording";
var stream = await recordStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
playbackElement.AutoPlay = true;
playbackElement.SetSource(stream, recordStorageFile.FileType);
playbackElement.Play();
recording = false;
}
}
catch (Exception ex)
{
recording = false;
new Windows.UI.Popups.MessageDialog(ex.Message).ShowAsync();
}
}
Download Demo Project