Exemple #1
0
        private async Task <bool> SetupRecordProcess()
        {
            if (buffer != null)
            {
                buffer.Dispose();
            }
            buffer = new InMemoryRandomAccessStream();

            if (capture != null)
            {
                capture.Dispose();
            }

            try
            {
                MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Audio
                };
                capture = new MediaCapture();
                await capture.InitializeAsync(settings);

                capture.RecordLimitationExceeded += RecordLimitExceedEventHandler;
                capture.Failed += CaptureFailedEventHandler;
            }
            catch (Exception ex)
            {
                ThrowException(ex);
                return(false);
            }
            return(true);
        }
        /**
         * カレント位置のサムネイルを作成する。
         */
        private async void createThumbnailCore()
        {
            if (mDoneOnce)
            {
                return;
            }
            mDoneOnce = true;

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() =>
            {
                CanvasDevice canvasDevice = CanvasDevice.GetSharedDevice();

                // Debug.WriteLine(mPlayerElement.MediaPlayer.PlaybackSession.Position);

                double mw             = mPlayerElement.MediaPlayer.PlaybackSession.NaturalVideoWidth, mh = mPlayerElement.MediaPlayer.PlaybackSession.NaturalVideoHeight;
                var limit             = Math.Min(Math.Max(mh, mw), 1024);
                var playerSize        = calcFittingSize(mw, mh, limit, limit);
                var canvasImageSource = new CanvasImageSource(canvasDevice, (int)playerSize.Width, (int)playerSize.Height, DisplayInformation.GetForCurrentView().LogicalDpi);//96);

                using (var frameServerDest = new SoftwareBitmap(BitmapPixelFormat.Rgba8, (int)playerSize.Width, (int)playerSize.Height, BitmapAlphaMode.Ignore))
                    using (CanvasBitmap canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(canvasDevice, frameServerDest))
                    {
                        mPlayerElement.MediaPlayer.CopyFrameToVideoSurface(canvasBitmap);
                        // ↑これで、frameServerDest に描画されるのかと思ったが、このframeServerDestは、単に、空のCanvasBitmapを作るための金型であって、
                        // 実際の描画は、CanvasBitmap(IDirect3DSurface)に対してのみ行われ、frameServerDestはからBitmapを作っても、黒い画像しか取り出せない。
                        // このため、有効な画像を取り出すには、CangasBitmapから softwareBitmapを生成してエンコードする必要がある。

                        using (var softwareBitmap = await SoftwareBitmap.CreateCopyFromSurfaceAsync(canvasBitmap))
                        {
                            var stream            = new InMemoryRandomAccessStream();
                            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
                            encoder.SetSoftwareBitmap(softwareBitmap);

                            try
                            {
                                await encoder.FlushAsync();
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e);
                                stream.Dispose();
                                stream = null;
                            }

                            if (null != mOnSelected)
                            {
                                mOnSelected(this, mPlayerElement.MediaPlayer.PlaybackSession.Position.TotalMilliseconds, stream);
                                closeDialog();
                            }
                            else
                            {
                                stream.Dispose();
                            }
                        }
                    }
            });
        }
        /// <summary>
        /// Register face to Cognitive Face API
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        private async Task <Person> RegisterAsync(InMemoryRandomAccessStream stream)
        {
            if (SelectedRSVP == null)
            {
                Message = "Select your RSVP.";
            }

            while (SelectedRSVP == null)
            {
                await Task.Delay(1000);
            }

            // All the members should be registered when initialized.
            var registeredPerson = registeredPersons.First(x => x.Name == SelectedRSVP.Member.Name);

            // Register face information and discard image.
            var addPersistedFaceResult = await faceClient.AddPersonFaceAsync(
                Settings.PersonGroupId, registeredPerson.PersonId, ImageConverter.ConvertImage(stream));

            stream.Dispose();

            await faceClient.TrainPersonGroupAsync(Settings.PersonGroupId);

            return(await faceClient.GetPersonAsync(Settings.PersonGroupId, registeredPerson.PersonId));
        }
Exemple #4
0
        private async Task <Result> GetCameraImage(CancellationToken cancelToken)
        {
            if (cancelToken.IsCancellationRequested)
            {
                throw new OperationCanceledException(cancelToken);
            }

            imageStream = new InMemoryRandomAccessStream();

            await capture.CapturePhotoToStreamAsync(encodingProps, imageStream);

            await imageStream.FlushAsync();

            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            byte[] pixels =
                (await
                 decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8,
                                           BitmapAlphaMode.Ignore,
                                           new BitmapTransform(),
                                           ExifOrientationMode.IgnoreExifOrientation,
                                           ColorManagementMode.DoNotColorManage)).DetachPixelData();

            const BitmapFormat format = BitmapFormat.RGB32;

            imageStream.Dispose();

            var result =
                await
                Task.Run(
                    () => barcodeReader.Decode(pixels, (int)decoder.PixelWidth, (int)decoder.PixelHeight, format),
                    cancelToken);

            return(result);
        }
Exemple #5
0
        public static async Task <string> ExtractTextAsync(Image img, string lang)
        {
            MemoryStream memoryStream             = new MemoryStream();
            InMemoryRandomAccessStream randStream = new InMemoryRandomAccessStream();
            string result = "";

            try
            {
                img.Save(memoryStream, ImageFormat.Bmp);
                await randStream.WriteAsync(memoryStream.ToArray().AsBuffer());

                if (!OcrEngine.IsLanguageSupported(new Language(lang)))
                {
                    Console.Write("This language is not supported!");
                }
                OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(new Language(lang));
                if (ocrEngine == null)
                {
                    ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages();
                }
                var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(randStream);

                OcrResult ocrResult = await ocrEngine.RecognizeAsync(await decoder.GetSoftwareBitmapAsync());

                result = ocrResult.Text;
                return(result);
            }
            finally
            {
                memoryStream.Dispose();
                randStream.Dispose();
                GC.Collect(0);
            }
        }
Exemple #6
0
    private async Task <bool> init()
    {
        if (stream != null)
        {
            stream.Dispose();
        }

        if (capture != null)
        {
            capture.Dispose();
        }
        try
        {
            stream = new InMemoryRandomAccessStream();
            MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings
            {
                StreamingCaptureMode = StreamingCaptureMode.Audio,
            };
            capture = new MediaCapture();
            await capture.InitializeAsync(settings);
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UnauthorizedAccessException))
            {
                throw ex.InnerException;
            }
            throw;
        }
        return(true);
    }
Exemple #7
0
 public void DisposeMemoryBuffer()
 {
     if (_memoryBuffer != null)
     {
         _memoryBuffer.Dispose();
     }
 }
        public static async Task <string> SendImage()
        {
            try
            {
                if (MainPage.oldImg == null)
                {
                    return("");
                }

                var stream = new InMemoryRandomAccessStream();

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                encoder.SetSoftwareBitmap(MainPage.oldImg);
                await encoder.FlushAsync();

                var ms = new MemoryStream();
                stream.AsStream().CopyTo(ms);
                var tdata = ms.ToArray();

                var x = Convert.ToBase64String(tdata);

                ms.Dispose();
                stream.Dispose();
                return(x);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return("");
            }
        }
Exemple #9
0
        public async void Record(object sender, RoutedEventArgs e)
        {
            // begin recording
            if (StartRecording == false)
            {
                //await Initialize();
                //await DeleteExistingFile();
                if (record_buffer != null)
                {
                    record_buffer.Dispose();
                }
                record_buffer = new InMemoryRandomAccessStream();
                MediaCaptureInitializationSettings settings =
                    new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Audio
                };
                captureManager_record = new MediaCapture();
                await captureManager_record.InitializeAsync(settings);

                await captureManager_record.StartRecordToStreamAsync(
                    MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto), record_buffer);

                StartRecording = true;
            }
            // stop recording
            else
            {
                await captureManager_record.StopRecordAsync();

                //SaveAudioToFile();
                //SaveToFile(record_buffer, false);
                StartRecording = false;
            }
        }
Exemple #10
0
        private void CaptureCameraSnapshot()
        {
            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                animCameraTimer.Stop();
                animCameraTimer.Begin();
            });

            if (_mediaCapture.CameraStreamState != Windows.Media.Devices.CameraStreamState.Streaming)
            {
                return;
            }
            IRandomAccessStream stream = new InMemoryRandomAccessStream();

            try
            {
                IAsyncAction action = _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
                action.Completed = (result, status) =>
                {
                    if (status == AsyncStatus.Completed)
                    {
                        OnCapturePhotoCompleted(stream, result, status);
                    }
                };
            }
            catch (Exception)
            {
                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }
            }
        }
 public void Dispose()
 {
     if (can == null)
     {
         GC.SuppressFinalize(this);
         return;
     }
     can.Children.Clear();
     GC.SuppressFinalize(can);
     GC.SuppressFinalize(img);
     GC.SuppressFinalize(rta);
     GC.SuppressFinalize(SA);
     GC.SuppressFinalize(SR);
     GC.SuppressFinalize(SG);
     GC.SuppressFinalize(SB);
     GC.SuppressFinalize(TA);
     GC.SuppressFinalize(TR);
     GC.SuppressFinalize(TG);
     GC.SuppressFinalize(TB);
     GC.SuppressFinalize(cancel);
     GC.SuppressFinalize(ok);
     GC.SuppressFinalize(bor);
     memoryStream.Dispose();
     memoryStreamA.Dispose();
     GC.SuppressFinalize(this);
 }
Exemple #12
0
        /// <inheritdoc/>
        public override async Task <(Stream stream, Exception error)> OpenEntryAsync(string entry)
        {
            var(irs, error) = await this.OpenEntryAsRandomAccessStreamAsync(entry);

            if (error != null)
            {
                return(null, error);
            }

            var decoder = await BitmapDecoder.CreateAsync(irs);

            var bitmap = decoder.GetSoftwareBitmapAsync();

            var outputIrs = new InMemoryRandomAccessStream();

            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, outputIrs);

            encoder.SetSoftwareBitmap(await bitmap);

            await encoder.FlushAsync();

            var outputStream = new MemoryStream();

            outputIrs.Seek(0);
            outputIrs.AsStreamForRead().CopyTo(outputStream);

            outputIrs.Dispose();
            outputStream.Seek(0, SeekOrigin.Begin);

            return(outputStream, null);
        }
Exemple #13
0
        /// <summary>
        /// Compresses the content and returns it as an input stream.
        /// </summary>
        /// <returns>A <see cref="IInputStream"/> implementation containing the compresssed data.</returns>
        public IAsyncOperationWithProgress <IInputStream, ulong> ReadAsInputStreamAsync()
        {
            return(AsyncInfo.Run <IInputStream, ulong>(async(cancellationToken, progress) =>
            {
                await BufferAllAsync().AsTask().ConfigureAwait(false);

                var randomAccessStream = new InMemoryRandomAccessStream();
                try
                {
                    using (var writer = new DataWriter(randomAccessStream))
                    {
                        writer.WriteBuffer(bufferedData);

                        uint bytesStored = await writer.StoreAsync().AsTask(cancellationToken);

                        // Make sure that the DataWriter destructor does not close the stream.
                        writer.DetachStream();

                        // Report progress.
                        progress.Report(randomAccessStream.Size);

                        return randomAccessStream.GetInputStreamAt(0);
                    }
                }
                catch
                {
                    randomAccessStream?.Dispose();
                    throw;
                }
            }));
        }
        private async Task SaveAsync()
        {
            var stream = new InMemoryRandomAccessStream();
            await ImageCropper.SaveAsync(stream, BitmapFileFormat.Png);

            App.ViewModel.IsLoading = true;
            var dispatcherQueue = Windows.System.DispatcherQueue.GetForCurrentThread();
            var data            = await App.Repository.User.UploadAvatarAsync(stream, async res =>
            {
                await dispatcherQueue.EnqueueAsync(() =>
                {
                    App.ViewModel.IsLoading = false;
                    _ = new MessageDialog(res.Message ?? Constants.GetString("unknow_error")).ShowAsync();
                });
            });

            stream.Dispose();
            await dispatcherQueue.EnqueueAsync(() =>
            {
                App.ViewModel.IsLoading = false;
                if (data == null)
                {
                    return;
                }
                App.ViewModel.User = data;
                Frame.GoBack();
            });
        }
        private async Task <bool> RecordProcess()
        {
            if (buffer != null)
            {
                buffer.Dispose();
            }
            buffer = new InMemoryRandomAccessStream();
            if (capture != null)
            {
                capture.Dispose();
            }
            try
            {
                MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Audio
                };
                capture = new MediaCapture();
                await capture.InitializeAsync(settings);

                capture.RecordLimitationExceeded += (MediaCapture sender) =>
                {
                    throw new Exception("Record Limitation Exceeded ");
                };
                capture.Failed += (MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) =>
                {
                    throw new Exception(string.Format("Code: {0}. {1}", errorEventArgs.Code, errorEventArgs.Message));
                };
            }
            catch (Exception ex)
            {
                throw;
            }
            return(true);
        }
Exemple #16
0
        private async void DisplayRecord(string hexInput)
        {
            try
            {
                InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(HexStringToByteArray(hexInput));
                    await writer.StoreAsync();

                    var iSC = new InkStrokeContainer();

                    await SampleInkCanvas.InkPresenter.StrokeContainer.LoadAsync(stream);

                    SampleInkCanvas.Width  = SampleInkCanvas.InkPresenter.StrokeContainer.BoundingRect.Right;
                    SampleInkCanvas.Height = SampleInkCanvas.InkPresenter.StrokeContainer.BoundingRect.Bottom;

                    StrokeTextBlock.Text = "Number of Strokes: " + SampleInkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count.ToString();
                }
                stream.Dispose();
            }
            catch (Exception ex)
            {
                ErrorDisplay.ShowErrorMessage(ex.Message);
            }
        }
        private static async void AddStrokeCountToRecords(List <InkSample> records)
        {
            foreach (InkSample record in records)
            {
                string hexInput = record.ISF;
                try
                {
                    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                    using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
                    {
                        writer.WriteBytes(HexStringToByteArray(hexInput));
                        await writer.StoreAsync();

                        var iSC = new InkStrokeContainer();

                        await iSC.LoadAsync(stream);


                        record.StrokeCount = iSC.GetStrokes().Count;
                    }
                    stream.Dispose();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error parsing ISF!");
                }
            }
        }
        private async void Run()
        {
            await _HubConnection.Start();

            var cam = new MediaCapture();

            await cam.InitializeAsync(new MediaCaptureInitializationSettings()
            {
                MediaCategory        = MediaCategory.Media,
                StreamingCaptureMode = StreamingCaptureMode.Video
            });

            _Sensor.MotionDetected += async(int pinNum) =>
            {
                var    stream      = new InMemoryRandomAccessStream();
                Stream imageStream = null;
                try
                {
                    await Task.Factory.StartNew(async() =>
                    {
                        _Sensor.IsActive = false;
                        await cam.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
                        stream.Seek(0);
                        imageStream = stream.AsStream();
                        imageStream.Seek(0, SeekOrigin.Begin);
                        string imageUrl = await NotificationHelper.UploadImageAsync(imageStream);

                        switch (await OxfordHelper.IdentifyAsync(imageUrl))
                        {
                        case AuthenticationResult.IsOwner:
                            // open the door
                            MotorController.PWM(26);
                            break;

                        case AuthenticationResult.Unkown:
                            // send notification to the owner
                            NotificationHelper.NotifyOwnerAsync(imageUrl);
                            break;

                        case AuthenticationResult.None:
                        default:
                            break;
                        }
                        _Sensor.IsActive = true;
                    });
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                    if (imageStream != null)
                    {
                        imageStream.Dispose();
                    }
                }
            };
        }
Exemple #19
0
        public async Task <StorageFile> CapturePhotoAsync()
        {
            if (_mediaCapture == null)
            {
                return(null);
            }

            var stream = new InMemoryRandomAccessStream();

            await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

            try
            {
                var filename = "adventure_" + DateTime.Now.ToString("HHmmss_MMddyyyy") + ".jpg";

                var file = await(await AdventureObjectStorageHelper.GetDataSaveFolder()).CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);

                using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(stream);

                    var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

                    var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
                    var properties       = new BitmapPropertySet {
                        { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, Windows.Foundation.PropertyType.UInt16) }
                    };

                    await encoder.BitmapProperties.SetPropertiesAsync(properties);

                    await encoder.FlushAsync();
                }

                stream.Dispose();
                PictureCaptured?.Invoke(this, new PictureCapturedEventArgs()
                {
                    File = file
                });
                return(file);
            }
            catch (Exception ex)
            {
                stream.Dispose();
                return(null);
            }
        }
        protected override void SubclassDispose()
        {
            bufferTaskCancelTokenSource.Cancel();
            bufferTaskCancelTokenSource.Dispose();

            clonedBufferStream.Dispose();
            bufferStream.Dispose();
        }
Exemple #21
0
        private async Task LoadImageFromHttpResponse(HttpResponseMessage response, BitmapImage bitmap, string cacheKey)
        {
            if (response.IsSuccessStatusCode)
            {
                var stream = new InMemoryRandomAccessStream();

                using (var content = response.Content)
                {
                    await content.WriteToStreamAsync(stream);
                }

                await stream.FlushAsync();

                stream.Seek(0);

                await bitmap.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() =>
                {
                    try
                    {
                        await bitmap.SetSourceAsync(stream);

                        // cache image asynchronously, after successful decoding
                        var task = Task.Run(async() =>
                        {
                            var buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);

                            stream.Seek(0);
                            await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);
                            stream.Dispose();

                            await Cache.SetAsync(cacheKey, buffer);
                        });
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("{0}: {1}", response.RequestMessage.RequestUri, ex.Message);
                        stream.Dispose();
                    }
                });
            }
            else
            {
                Debug.WriteLine("{0}: {1}", response.RequestMessage.RequestUri, response.StatusCode);
            }
        }
Exemple #22
0
        private async void OnButtonClicked(object sender, RoutedEventArgs e)
        {
            if (!_recording)
            {
                MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Audio
                };

                _capture = new MediaCapture();
                await _capture.InitializeAsync(settings);

                _capture.RecordLimitationExceeded += async(MediaCapture s) =>
                {
                    await new MessageDialog("Record limtation exceeded", "Error").ShowAsync();
                };

                _capture.Failed += async(MediaCapture s, MediaCaptureFailedEventArgs args) =>
                {
                    await new MessageDialog("Media capture failed: " + args.Message, "Error").ShowAsync();
                };

                _buffer = new InMemoryRandomAccessStream();
                var profile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);
                profile.Audio = AudioEncodingProperties.CreatePcm(16000, 1, 16); // Must be mono (1 channel)
                await _capture.StartRecordToStreamAsync(profile, _buffer);

                TheButton.Content = "Verify";
                _recording        = true;
            }
            else // Recording
            {
                if (_capture != null && _buffer != null && _id != null && _id != Guid.Empty)
                {
                    await _capture.StopRecordAsync();

                    IRandomAccessStream stream = _buffer.CloneStream();
                    var client = new SpeakerVerificationServiceClient(_key);

                    var response = await client.VerifyAsync(stream.AsStream(), _id);

                    string message = String.Format("Result: {0}, Confidence: {1}", response.Result, response.Confidence);
                    await new MessageDialog(message).ShowAsync();

                    _capture.Dispose();
                    _capture = null;

                    _buffer.Dispose();
                    _buffer = null;
                }

                TheButton.Content = "Start";
                _recording        = false;
            }
        }
Exemple #23
0
        async private void openCamera(object sender, RoutedEventArgs e)
        {
            if (StartVideo == false)
            {
                //camera.Icon = IconElement.
                if (video_buffer != null)
                {
                    video_buffer.Dispose();
                }
                video_buffer              = new InMemoryRandomAccessStream();
                showVideo.Visibility      = Visibility.Collapsed;
                capturePreview.Visibility = Visibility.Visible;
                //ProfilePic.Visibility = Visibility.Collapsed;
                captureManager_video = new MediaCapture();
                //选择后置摄像头
                var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

                if (cameraDevice == null)
                {
                    System.Diagnostics.Debug.WriteLine("No camera device found!");
                    return;
                }
                var settings = new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Video,
                    //MediaCategory = MediaCategory.Other,
                    //AudioProcessing = AudioProcessing.Default,
                    //PhotoCaptureSource = PhotoCaptureSource.Photo,
                    AudioDeviceId = string.Empty,
                    VideoDeviceId = cameraDevice.Id
                };
                await captureManager_video.InitializeAsync(settings);

                //摄像头旋转90度
                //captureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                capturePreview.Source = captureManager_video;
                // await captureManager_video.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto), video_buffer);
                await captureManager_video.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto), video_buffer);

                await captureManager_video.StartPreviewAsync();

                //await captureManager_video.StartPreviewAsync();
                StartVideo = true;
            }
            else
            {
                await captureManager_video.StopRecordAsync();

                //SavaVideoToFile();
                SaveToFile(video_buffer, false);
                StartVideo = false;
            }
        }
Exemple #24
0
        /// <summary>
        /// Record a fragment of the given duration.
        /// </summary>
        /// <param name="duration">The desired duration in milliseconds.</param>
        /// <returns>The recorded fragmet as a RandomAccessStream object.</returns>
        public async Task <IRandomAccessStream> Record(int duration)
        {
            buffer?.Dispose();
            buffer = new InMemoryRandomAccessStream();
            await mediaCapture.StartRecordToStreamAsync(wavEncodingProfile, buffer);

            await Task.Delay(duration);

            await mediaCapture.StopRecordAsync();

            return(buffer.CloneStream());
        }
Exemple #25
0
        public async Task SendStreamAsync(MessageType messageType, InMemoryRandomAccessStream bits)
        {
            await this.SendAsync(
                messageType,
                (int)bits.Size,
                async() =>
            {
                await RandomAccessStream.CopyAsync(bits, this.socket.OutputStream);
            }
                );

            bits.Dispose();
        }
        ///
        ///  Name           ClearAudioFiles
        ///
        ///  <summary>     Clears the audio file after saving.
        ///  </summary>
        /// <returns></returns>
        public async void ClearAudioFiles()
        {
            try
            {
                await _buffer.FlushAsync();

                _buffer.Dispose();
            }
            catch (Exception ex)
            {
                LogTracking.LogTrace(ex.ToString());
            }
        }
        /// ------------------------------------------------------------------------------------------------

        /// -------------------------------------------------------------------------------------------------
        #region Private Functions
        ///
        /// Name        RecordProcess
        ///
        ///<summary>
        ///</summary>
        private async Task <bool> RecordProcess()
        {
            _buffer?.Dispose();
            _buffer = new InMemoryRandomAccessStream();
            _capture?.Dispose();
            _playaudio?.Dispose();
            try
            {
                MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Audio
                };
                _capture = new MediaCapture();
                await _capture.InitializeAsync(settings);

                _capture.RecordLimitationExceeded += sender =>
                {
                    _record = false;
                    throw new Exception("Record Limitation Exceeded ");
                };
                _capture.Failed += (sender, errorEventArgs) =>
                {
                    _record = false;
                    throw new Exception(string.Format("Code: {0}. {1}", errorEventArgs.Code, errorEventArgs.Message));
                };

                _playaudio = new MediaCapture();
                await _playaudio.InitializeAsync(settings);

                _playaudio.RecordLimitationExceeded += sender =>
                {
                    _record = false;
                    throw new Exception("Record Limitation Exceeded ");
                };
                _playaudio.Failed += (sender, errorEventArgs) =>
                {
                    _record = false;
                    throw new Exception(string.Format("Code: {0}. {1}", errorEventArgs.Code, errorEventArgs.Message));
                };
            }
            catch (Exception ex)
            {
                LogTracking.LogTrace(ex.ToString());
                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UnauthorizedAccessException))
                {
                    throw ex.InnerException;
                }
            }
            return(true);
        }
Exemple #28
0
        private async Task <byte[]> GetInkBytes()
        {
            IRandomAccessStream stream = new InMemoryRandomAccessStream();
            await InkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);

            byte[] buffer = new byte[stream.Size];
            using (DataReader reader = new DataReader(stream.GetInputStreamAt(0UL)))
            {
                await reader.LoadAsync((uint)stream.Size);

                reader.ReadBytes(buffer);
            }
            stream.Dispose();
            return(buffer);
        }
Exemple #29
0
        private void Initialized()
        {
            if (_memoryBuffer != null)
            {
                _memoryBuffer.Dispose();
            }

            _memoryBuffer = new InMemoryRandomAccessStream();

            if (_mediaCapture != null)
            {
                _mediaCapture.Dispose();
            }

            this._fileName = DEFAULT_AUDIO_FILENAME + DateTime.Now + ".wav";
        }
Exemple #30
0
        private void Initialize()
        {
            if (_memoryBuffer != null)
            {
                _memoryBuffer.Dispose();
            }

            _memoryBuffer = new InMemoryRandomAccessStream();

            if (_mediaCapture != null)
            {
                _mediaCapture.Dispose();
            }
            _fileName = DEFAULT_AUDIO_FILENAME;
            UdpService.startup(ipAddress);
        }