Skip to content

Instantly share code, notes, and snippets.

@Ciwan1859
Created June 19, 2015 11:25
Show Gist options
  • Save Ciwan1859/4c06eaab21bc465cf766 to your computer and use it in GitHub Desktop.
Save Ciwan1859/4c06eaab21bc465cf766 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.IO;
using Windows.Media;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Newtonsoft.Json;
using Recorder.ViewModels;
using Recorder.Views.Dialogs;
namespace Recorder.Views
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private readonly MediaCapture _mediaCaptureManager;
private readonly StorageFolder _finalStorageFolder;
private readonly StorageFolder _tempStorageFolder;
private StorageFile _storageFile;
public bool Recording;
private readonly bool _userRequestedRaw;
private readonly bool _rawAudioSupported;
#pragma warning disable 414
private string _fileName;
#pragma warning restore 414
private DispatcherTimer _timer;
private bool _sliderpressed = false;
// Constructor
public MainPage()
{
InitializeComponent();
NavigationCacheMode = NavigationCacheMode.Required;
_mediaCaptureManager = new MediaCapture();
Recording = false;
_fileName = "Un-named";
_userRequestedRaw = false;
_rawAudioSupported = false;
_finalStorageFolder = ApplicationData.Current.LocalFolder;
_tempStorageFolder = ApplicationData.Current.TemporaryFolder;
//AudioPlayerSeek.ValueChanged += AudioPlayerSeek_ValueChanged;
//PointerEventHandler pointerpressedhandler = new PointerEventHandler(slider_PointerEntered);
//AudioPlayerSeek.AddHandler(Control.PointerPressedEvent, pointerpressedhandler, true);
//PointerEventHandler pointerreleasedhandler = new PointerEventHandler(slider_PointerCaptureLost);
//AudioPlayerSeek.AddHandler(Control.PointerCaptureLostEvent, pointerreleasedhandler, true);
InitializeAudioRecording();
DataContext = App.ViewModel;
}
/// <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)
{
}
// Control Event Handlers
private void BtnRecord_OnChecked(object sender, RoutedEventArgs e)
{
//EpsIndicator.Fill = new SolidColorBrush(Color.FromArgb(255, 114, 191, 141));
AnimateRecordEps.Begin();
var symbol = new SymbolIcon(Symbol.Stop) { Foreground = new SolidColorBrush(Colors.Black) };
BtnRecord.Content = symbol;
CaptureAudio();
}
private void BtnRecord_OnUnchecked(object sender, RoutedEventArgs e)
{
EpsRecord.Fill = new SolidColorBrush(Color.FromArgb(255, 183, 71, 29));
var symbol = new SymbolIcon(Symbol.Microphone) { Foreground = new SolidColorBrush(Colors.Black) };
BtnRecord.Content = symbol;
StopCapture();
}
private void BtnPlay_OnChecked(object sender, RoutedEventArgs e)
{
//EpsPlay.Fill = new SolidColorBrush(Color.FromArgb(255, 159, 191, 114));
AnimatePlayEps.Begin();
var symbol = new SymbolIcon(Symbol.Stop) { Foreground = new SolidColorBrush(Colors.Black) };
BtnPlay.Content = symbol;
StartPlay();
}
private void BtnPlay_OnUnchecked(object sender, RoutedEventArgs e)
{
SetBtnPlayToPlayIcon();
StopPlay();
}
private async void BtnSaveRecordedAudio_OnClick(object sender, RoutedEventArgs e)
{
// New ContentDialog instance
var savingForm = new RecordingFileName();
// Display dialog
var result = await savingForm.ShowAsync();
// Check result of dialog
if (result == ContentDialogResult.Primary)
{
_fileName = savingForm.FileName.Text;
var file = new RecordFileVm { Title = _fileName, FileName = _fileName.Replace(" ", "").ToLower(), RecordedOn = DateTime.Now };
_storageFile.MoveAsync(_finalStorageFolder, file.FileName);
App.ViewModel.Files.Add(file);
var jsonData = JsonConvert.SerializeObject(App.ViewModel.Files);
// Get the LocalSettings object
var localSettings = ApplicationData.Current.LocalSettings;
// Overwrite or Create new key with up to date data
localSettings.Values[RecordsVm.DataKey] = jsonData;
}
// clear source property on MediaElement
RecordReplayPlayer.Source = null;
// hide app bar
CommandBar.Visibility = Visibility.Collapsed;
// hide Grid hoousing the play back elements
PlayBackGrid.Visibility = Visibility.Collapsed;
}
// Clicking item in Library
private async void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Cast to XAML ListView
var listView = sender as ListView;
// Verify we have ListView
if (listView == null) { return; }
var listVmItem = listView.SelectedItem as RecordFileVm;
if (listVmItem != null)
{
var file2 = await _finalStorageFolder.GetFileAsync(listVmItem.FileName);
var stream = (await file2.OpenReadAsync()).AsStream().AsRandomAccessStream();
LibraryAudioPlayer.SetSource(stream, file2.ContentType);
LibraryAudioPlayer.MediaOpened += LibraryAudioPlayer_MediaOpened;
LibraryAudioPlayer.CurrentStateChanged += LibraryAudioPlayer_CurrentStateChanged;
}
// Clear selection
listView.SelectedItem = null;
}
private void UIElement_OnHolding(object sender, HoldingRoutedEventArgs e)
{
var senderElement = sender as FrameworkElement;
var flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement);
flyoutBase.ShowAt(senderElement);
}
private async void RemoveRecordedFile_OnClick(object sender, RoutedEventArgs e)
{
// Grab RecordFileVM
var frameworkElement = e.OriginalSource as FrameworkElement;
if (frameworkElement != null)
{
var recordedFile = frameworkElement.DataContext as RecordFileVm;
// Remove file from app ViewModel
App.ViewModel.Files.Remove(recordedFile);
// Remove file from permenant local storage
if (recordedFile != null)
{
var fileInStorage = await _finalStorageFolder.GetFileAsync(recordedFile.FileName);
fileInStorage.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
}
// Update List of Recorded Files
var jsonData = JsonConvert.SerializeObject(App.ViewModel.Files);
// Get the LocalSettings object
var localSettings = ApplicationData.Current.LocalSettings;
// Overwrite or Create new key with up to date data
localSettings.Values[RecordsVm.DataKey] = jsonData;
}
private void LibraryAudioPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
var recordingTime = LibraryAudioPlayer.NaturalDuration.TimeSpan;
AudioPlayerSeek.Maximum = recordingTime.TotalSeconds;
SetupTimer();
}
// Error Event Handlers
private static void RecordLimitationExceeded(MediaCapture sender)
{
Debug.WriteLine("Record Limit Exceeded!");
}
private static void FailedCapture(MediaCapture sender, MediaCaptureFailedEventArgs e)
{
Debug.WriteLine("Failed to capture!");
}
// Helper Methods
private async void InitializeAudioRecording()
{
var settings = new MediaCaptureInitializationSettings
{
StreamingCaptureMode = StreamingCaptureMode.Audio,
MediaCategory = MediaCategory.Other,
AudioProcessing = (_rawAudioSupported && _userRequestedRaw) ? AudioProcessing.Raw : AudioProcessing.Default
};
await _mediaCaptureManager.InitializeAsync(settings);
_mediaCaptureManager.RecordLimitationExceeded += new RecordLimitationExceededEventHandler(RecordLimitationExceeded);
_mediaCaptureManager.Failed += new MediaCaptureFailedEventHandler(FailedCapture);
}
private async void StartPlay()
{
if (Recording) return;
var stream = await _storageFile.OpenAsync(FileAccessMode.Read);
RecordReplayPlayer.AutoPlay = true;
RecordReplayPlayer.SetSource(stream, _storageFile.FileType);
RecordReplayPlayer.Play();
}
private void StopPlay()
{
RecordReplayPlayer.AutoPlay = false;
RecordReplayPlayer.Stop();
}
private void AudioPlayer_OnMediaEnded(object sender, RoutedEventArgs e)
{
SetBtnPlayToPlayIcon();
}
private void SetBtnPlayToPlayIcon()
{
EpsPlay.Fill = new SolidColorBrush(Color.FromArgb(255, 114, 191, 141));
var symbol = new SymbolIcon(Symbol.Play) { Foreground = new SolidColorBrush(Colors.Black) };
BtnPlay.Content = symbol;
}
private async void CaptureAudio()
{
try
{
const string fileName = "tempRecording.wav";
//_storageFile = await KnownFolders.MusicLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
_storageFile = await _tempStorageFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
var recordProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);
await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, _storageFile);
Recording = true;
}
catch (Exception e)
{
Debug.WriteLine("Failed to capture audio");
}
}
private async void StopCapture()
{
if (!Recording) return;
await _mediaCaptureManager.StopRecordAsync();
Recording = false;
PlayBackGrid.Visibility = Visibility.Visible;
CommandBar.Visibility = Visibility.Visible;
}
private void SetupTimer()
{
_timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) };
StartTimer();
}
private void StartTimer()
{
_timer.Tick += _timer_Tick;
_timer.Start();
LibraryAudioPlayer.Play();
}
private void _timer_Tick(object sender, object e)
{
if (!_sliderpressed)
{
AudioPlayerSeek.Value = LibraryAudioPlayer.Position.TotalSeconds;
}
}
private double SliderFrequency(TimeSpan timevalue)
{
double stepfrequency = -1;
double absvalue = (int)Math.Round(timevalue.TotalSeconds, MidpointRounding.AwayFromZero);
stepfrequency = (int)(Math.Round(absvalue / 100));
if (timevalue.TotalMinutes >= 10 && timevalue.TotalMinutes < 30)
{
stepfrequency = 10;
}
else if (timevalue.TotalMinutes >= 30 && timevalue.TotalMinutes < 60)
{
stepfrequency = 30;
}
else if (timevalue.TotalHours >= 1)
{
stepfrequency = 60;
}
if (stepfrequency == 0) stepfrequency += 1;
if (stepfrequency == 1)
{
stepfrequency = absvalue / 100;
}
return stepfrequency;
}
void slider_PointerEntered(object sender, PointerRoutedEventArgs e)
{
_sliderpressed = true;
}
void slider_PointerCaptureLost(object sender, PointerRoutedEventArgs e)
{
LibraryAudioPlayer.Position = TimeSpan.FromSeconds(AudioPlayerSeek.Value);
_sliderpressed = false;
}
void LibraryAudioPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
{
if (LibraryAudioPlayer.CurrentState == MediaElementState.Paused)
{
_timer.Stop();
}
if (LibraryAudioPlayer.CurrentState == MediaElementState.Stopped)
{
_timer.Stop();
AudioPlayerSeek.Value = 0;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment