Ejemplo n.º 1
0
        public async Task <IRandomAccessStream> StartDownload(Uri uri)
        {
            byte[] bytes = null;
            TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, 0, bytes));
            cts = new CancellationTokenSource();
            DownloadBytesCount = new DownLoadBytes();

            var stream = await GetAsyncStreamDownLoad(uri, cts.Token);

            if (!cts.IsCancellationRequested && stream != null)
            {
                using (stream)
                {
                    var randomAccessStream = new InMemoryRandomAccessStream();
                    var outputStream       = randomAccessStream.GetOutputStreamAt(0);
                    await RandomAccessStream.CopyAsync(stream.AsInputStream(), outputStream);

                    DownloadBytesCount.BytesReceived = Convert.ToInt64(randomAccessStream.Size);
                    var    randomAccessStreamTemp = randomAccessStream.CloneStream();
                    Stream streamTemp             = WindowsRuntimeStreamExtensions.AsStreamForRead(randomAccessStreamTemp.GetInputStreamAt(0));
                    var    bytesTemp = ConvertStreamTobyte(streamTemp);
                    TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, 100, bytesTemp));
                    //TriggerDownLoadComplete(new DownLoadCompleteEventArgs(randomAccessStream));
                    TriggerDownLoadComplete(new DownLoadCompleteEventArgs(randomAccessStream.CloneStream()));
                    return(randomAccessStream as IRandomAccessStream);
                }
            }
            return(null);
        }
Ejemplo n.º 2
0
    public async Task Play(CoreDispatcher dispatcher, MediaElement playback)
    {
        IRandomAccessStream video = buffer.CloneStream();

        if (video == null)
        {
            throw new ArgumentNullException("buffer");
        }
        StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

        if (!string.IsNullOrEmpty(filename))
        {
            StorageFile original = await storageFolder.GetFileAsync(filename);

            await original.DeleteAsync();
        }
        await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
        {
            StorageFile storageFile = await storageFolder.CreateFileAsync(videoFilename, CreationCollisionOption.GenerateUniqueName);
            filename = storageFile.Name;
            using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(video.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                await video.FlushAsync();
                video.Dispose();
            }
            IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);
            playback.SetSource(stream, storageFile.FileType);
            playback.Play();
        });
    }
Ejemplo n.º 3
0
        public async Task SaveRecordedAudio(CoreDispatcher UiDispatcher)
        {
            IRandomAccessStream audio = buffer.CloneStream();

            if (audio == null)
            {
                throw new ArgumentNullException("buffer");
            }

            //StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            /*
             * StorageFolder storageFolder = await DownloadsFolder.;
             * if (!string.IsNullOrEmpty(filename))
             * {
             *  StorageFile original = await storageFolder.GetFileAsync(filename);
             *  await original.DeleteAsync();
             * }
             */
            await UiDispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                //StorageFile storageFile = await storageFolder.CreateFileAsync(audioFile, CreationCollisionOption.GenerateUniqueName);
                StorageFile storageFile = await DownloadsFolder.CreateFileAsync(audioFile, CreationCollisionOption.GenerateUniqueName);
                filename = storageFile.Name;
                using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                    await audio.FlushAsync();
                    audio.Dispose();
                }
                //IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);

                LogMessage($"File {storageFile.Name} saved to {storageFile.Path}");
            });
        }
Ejemplo n.º 4
0
        public async Task Play(CoreDispatcher dispatcher)
        {
            LoggingMsg("Playing audio...");
            MediaElement        playback = new MediaElement();
            IRandomAccessStream audio    = buffer.CloneStream();

            if (audio == null)
            {
                throw new ArgumentNullException("buffer");
            }
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

            if (!string.IsNullOrEmpty(filename))
            {
                StorageFile original = await storageFolder.GetFileAsync(filename);

                await original.DeleteAsync();
            }
            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                recordingFile = await storageFolder.CreateFileAsync(RECORDING_FILE, CreationCollisionOption.ReplaceExisting);
                filename      = recordingFile.Name;
                using (IRandomAccessStream fileStream = await recordingFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                    await audio.FlushAsync();
                    audio.Dispose();
                }

                IRandomAccessStream stream = await recordingFile.OpenAsync(FileAccessMode.Read);
                playback.SetSource(stream, recordingFile.FileType);
                //Time.Text = playback.NaturalDuration.TimeSpan.TotalSeconds.ToString();
                playback.Play();
            });
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Saves the audio to a file in our local state folder
        /// </summary>
        /// <returns>the saved file's name</returns>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        public async Task <string> SaveAudioToFile()
        {
            string        dateToday        = DateTime.Now.ToString("yyyy-MM-dd");
            string        ticks            = DateTime.Now.Ticks.ToString();
            string        mp3              = ".mp3";
            string        fileName         = String.Format("record_{0}_{1}{2}", dateToday, ticks, mp3);
            StorageFolder localStateFolder = ApplicationData.Current.LocalFolder;
            StorageFolder storageFolder;

            if (!Directory.Exists(Path.Combine(localStateFolder.Path, "VoiceNotes")))
            {
                storageFolder = await localStateFolder.CreateFolderAsync("VoiceNotes");
            }
            else
            {
                storageFolder = await localStateFolder.GetFolderAsync("VoiceNotes");
            }
            IRandomAccessStream audioStream = _memoryBuffer.CloneStream();
            StorageFile         storageFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

            this._fileName = storageFile.Name;
            using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(audioStream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

                await audioStream.FlushAsync();

                audioStream.Dispose();
            }
            DisposeMemoryBuffer();

            return(this._fileName);
        }
Ejemplo n.º 6
0
        private async void SaveAudioToFile(InMemoryRandomAccessStream buffer)
        {
            try
            {
                IRandomAccessStream audioStream   = buffer.CloneStream();
                StorageFolder       storageFolder = Package.Current.InstalledLocation;

                StorageFile storageFile = await storageFolder.CreateFileAsync(DEFAULT_AUDIO_FILENAME, CreationCollisionOption.GenerateUniqueName);

                this._fileName = storageFile.Name;

                using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audioStream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

                    await audioStream.FlushAsync();

                    audioStream.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 7
0
        public async Task Play(CoreDispatcher dispatcher)
        {
            MediaElement        playback = new MediaElement();
            IRandomAccessStream audio    = buffer.CloneStream();

            if (audio == null)
            {
                throw new ArgumentNullException("buffer");
            }
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

            if (!string.IsNullOrEmpty(filename))
            {
                StorageFile original = await storageFolder.GetFileAsync(filename);

                await original.DeleteAsync();
            }
            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                StorageFile storageFile = await storageFolder.CreateFileAsync(audioFilename, CreationCollisionOption.ReplaceExisting);
                filename = storageFile.Name;
                using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                    await audio.FlushAsync();
                    audio.Dispose();
                }
                IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);
                playback.SetSource(stream, "");
                playback.Play();
            });
        }
Ejemplo n.º 8
0
        private async Task TakePhoto()
        {
            // Set properties of image(jpeg) and Capture a image into a new stream
            ImageEncodingProperties properties = ImageEncodingProperties.CreateJpeg();

            using (IRandomAccessStream ras = new InMemoryRandomAccessStream())
            {
                await this.capture.CapturePhotoToStreamAsync(properties, ras);

                await ras.FlushAsync();

                // Load the image into a BitmapImage set stream to 0 for next photo
                ras.Seek(0);
                var picLocation = new BitmapImage();
                picLocation.SetSource(ras);

                //place into listview
                var img = new Image()
                {
                    Width = 200, Height = 158
                };
                img.Source    = picLocation;
                Image1.Source = picLocation;
                //Clone the stream and use this to run api call
                rasClone = ras.CloneStream();
            }
        }
Ejemplo n.º 9
0
        public async Task <IRandomAccessStream> StopRecording()
        {
            await _mediaCapture.StopRecordAsync();

            IsRecording = false;
            return(_memoryBuffer.CloneStream());
        }
Ejemplo n.º 10
0
        async Task TakePicture()
        {
            try
            {
                using (var photo_stream = new InMemoryRandomAccessStream())
                {
                    Camera.VideoDeviceController.Focus.TrySetAuto(true);
                    await Camera.CapturePhotoToStreamAsync(_imageProperties, photo_stream);

                    photo_stream.Seek(0);
                    var decoder = await BitmapDecoder.CreateAsync(photo_stream);

                    var provider = await decoder.GetPixelDataAsync(
                        BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Ignore,
                        new BitmapTransform(),
                        ExifOrientationMode.IgnoreExifOrientation,
                        ColorManagementMode.ColorManageToSRgb);

                    _imageBuffer = provider.DetachPixelData();

                    _photoStream = photo_stream.CloneStream();
                }
            }
            catch (Exception ex)
            {
                StatusText.Text = ex.Message;
                Cleanup();
            }
        }
Ejemplo n.º 11
0
    public async Task PlayVoice(CoreDispatcher dispatcher) //Plays the voice recording back
    {
        MediaElement        playVoice = new MediaElement();
        IRandomAccessStream voice     = buffer.CloneStream();

        if (voice == null)
        {
            throw new ArgumentNullException("BUFFER");
        }
        StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

        if (!string.IsNullOrEmpty(appFile))
        {
            StorageFile sf = await appFolder.GetFileAsync(appFile);

            await sf.DeleteAsync();
        }
        await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
        {
            StorageFile file = await appFolder.CreateFileAsync(voiceFile, CreationCollisionOption.GenerateUniqueName);
            appFile          = file.Name;
            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(voice.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                await voice.FlushAsync();
                voice.Dispose();
            }
            IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
            playVoice.SetSource(stream, file.FileType);
            playVoice.Play();
        });
    }
Ejemplo n.º 12
0
        /// <summary>
        /// Captures audio from the microphone for the specified amount of time.
        /// </summary>
        /// <param name="ct"></param>
        /// <param name="timeToRecord">Amount of time to record.</param>
        /// <returns></returns>
        public async Task <Stream> RecordAsync(CancellationToken ct, TimeSpan timeToRecord)
        {
            MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings
            {
                StreamingCaptureMode = StreamingCaptureMode.Audio
            };

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

            var outProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Medium);

            outProfile.Audio = AudioEncodingProperties.CreatePcm(16000, 1, 16);

            var buffer = new InMemoryRandomAccessStream();
            await audioCapture.StartRecordToStreamAsync(outProfile, buffer);

            await Task.Delay(timeToRecord, ct);

            await audioCapture.StopRecordAsync();

            IRandomAccessStream audio = null;

            try
            {
                audio = buffer.CloneStream();
                return(this.FixWavPcmStream(audio));
            }
            finally
            {
                audio.Dispose();
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Record from the microphone and broadcast the buffer.
        /// </summary>
        async Task Record()
        {
            try
            {
                int readFailureCount = 0;

                using (var readStream = stream.CloneStream())
                    using (var reader = new DataReader(readStream))
                    {
                        reader.InputStreamOptions = InputStreamOptions.Partial;
                        //reader.UnicodeEncoding = UnicodeEncoding.Utf8;

                        while (Active)
                        {
                            try
                            {
                                //not sure if this is even a good idea (likely no), but we'll try to allow a single bad read, and past that shut it down
                                if (readFailureCount > 1)
                                {
                                    System.Diagnostics.Debug.WriteLine("AudioStream.Record(): Multiple read failures detected, stopping stream");
                                    await Stop();

                                    break;
                                }

                                var loadResult = await reader.LoadAsync(bufferSize);

                                //readResult should contain the # bytes read
                                if (loadResult > 0)
                                {
                                    byte[] bytes = new byte[loadResult];
                                    reader.ReadBytes(bytes);

                                    //System.Diagnostics.Debug.WriteLine("AudioStream.Record(): Read {0} bytes, broadcasting {1} bytes", loadResult, bytes.Length);

                                    OnBroadcast?.Invoke(this, bytes);
                                }
                                else
                                {
                                    //System.Diagnostics.Debug.WriteLine("AudioStream.Record(): Non positive readResult returned: {0}", loadResult);
                                }
                            }
                            catch (Exception ex)
                            {
                                readFailureCount++;

                                System.Diagnostics.Debug.WriteLine("Error in Android AudioStream.Record(): {0}", ex.Message);
                                OnException?.Invoke(this, ex);
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error in Android AudioStream.Record(): {0}", ex.Message);
                OnException?.Invoke(this, ex);
            }
        }
Ejemplo n.º 14
0
        private static async Task <Tuple <BitmapDecoder, IRandomAccessStream> > GetPhotoStreamAsync(
            MediaCapture mediaCapture)
        {
            InMemoryRandomAccessStream photoStream = new InMemoryRandomAccessStream();
            await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), photoStream);

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(photoStream);

            return(new Tuple <BitmapDecoder, IRandomAccessStream>(decoder, photoStream.CloneStream()));
        }
Ejemplo n.º 15
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;
            }
        }
Ejemplo n.º 16
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());
        }
Ejemplo n.º 17
0
        public void StartPlaying()
        {
            //var devices = await DeviceInformation.FindAllAsync();
            //string beingUsedDeviceId = null;

            //foreach (var device in devices)
            //{
            //Debug.WriteLine(device.Name);
            //if (device.Name.Equals("Speakers (Logitech USB Headset H340)"))
            //{
            //    beingUsedDeviceId = device.Id;
            //    Debug.WriteLine("Used " + device.Name);
            //    break;
            //}
            //}

            //var beingUsedDevice = await DeviceInformation.CreateFromIdAsync(beingUsedDeviceId);
            IRandomAccessStream tempBuffer = _memoryBuffer.CloneStream();
            var source = MediaSource.CreateFromStream(tempBuffer, "audio/mpeg");

            source.StateChanged += OnStateChanged;

            MediaPlayer _player = new MediaPlayer
            {
                //AutoPlay = true,
                RealTimePlayback = true,
                //CanPause = false,
                //AudioDevice = beingUsedDevice,
                Source = source
            };

            //_player.PlaybackSession.BufferingProgressChanged += OnBufferingProgressChanged;
            _player.PlaybackSession.PositionChanged += OnPositionChanged;
            _player.CurrentStateChanged             += OnCurrentStateChanged;
            _player.MediaEnded += OnMediaEnded;
            _player.Play();
            //_player.SourceChanged += OnSourceChanged;

            //new Task(() => StartBufferMonitoring(_player.PlaybackSession, source), TaskCreationOptions.LongRunning).Start();
        }
Ejemplo n.º 18
0
        internal async void InitPreviewImage()
        {
            if (this.Source == null)
            {
                return;
            }

            using (var fileStream = await this.Source.OpenReadAsync())
            {
                InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();

                using (var readStream = fileStream.GetInputStreamAt(0))
                {
                    var reader = new Windows.Storage.Streams.DataReader(readStream);
                    await reader.LoadAsync((uint)fileStream.Size);

                    byte[] bytes = new byte[fileStream.Size];
                    reader.ReadBytes(bytes);

                    var writeStream = memoryStream.GetOutputStreamAt(0).AsStreamForWrite();
                    writeStream.WriteAsync(bytes, 0, (int)fileStream.Size);
                    await writeStream.FlushAsync();
                }

                this.modifiedBitmapStream = memoryStream.CloneStream();
                this.previewBitmapStream  = this.modifiedBitmapStream;
            }

            var decoder = await BitmapDecoder.CreateAsync(this.previewBitmapStream);

            //   this.originalBitmapStream = await this.Source.OpenReadAsync();
            //  this.previewBitmapStream = await this.Source.OpenReadAsync();
            var properties = await this.Source.Properties.GetImagePropertiesAsync();

            System.Threading.SynchronizationContext.Current.Post((args) =>
            {
                System.Threading.SynchronizationContext.Current.Post((args2) =>
                {
                    this.previewBitmap  = new WriteableBitmap((int)properties.Width, (int)properties.Height);
                    this.originalBitmap = new WriteableBitmap((int)properties.Width, (int)properties.Height);
                    this.previewBitmap.SetSource(this.modifiedBitmapStream);
                    this.originalBitmap.SetSource(this.modifiedBitmapStream);

                    this.previewBitmap.Invalidate();
                    this.originalBitmap.Invalidate();

                    this.ModifiedImage = this.previewBitmap;
                }, null);
            }, null);
        }
Ejemplo n.º 19
0
        private async Task <IRandomAccessStream> GetThumbnailStreamAsync()
        {
#if DEBUG
            System.Diagnostics.Debug.WriteLine("GetThumbnailStreamAsync invoked " + this.GetHashCode());
#endif

            var maximumSide = (int)Windows.UI.Xaml.Application.Current.Resources["ThumbnailSide"];
            var orientation = await GetPhotoOrientationAsync();

            var orientationValue = orientation.HasValue ? orientation.Value : PhotoOrientation.Unspecified;

            using (var stream = await _file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView))
            {
                if (stream.ContentType == "image/jpeg")
                {
                    if ((stream.OriginalWidth <= maximumSide || stream.OriginalHeight <= maximumSide) && orientationValue == PhotoOrientation.Normal)
                    {
                        using (var memoryStream = new InMemoryRandomAccessStream())
                        {
                            using (var reader = new DataReader(stream))
                                using (var writer = new DataWriter(memoryStream))
                                {
                                    await reader.LoadAsync((uint)stream.Size);

                                    var buffer = reader.ReadBuffer((uint)stream.Size);

                                    writer.WriteBuffer(buffer);
                                    await writer.StoreAsync();

                                    await writer.FlushAsync();

                                    return(memoryStream.CloneStream());
                                }
                        }
                    }
                    else
                    {
                        return(await ResizeStreamAsync(stream, new Size(maximumSide, maximumSide), orientationValue));
                    }
                }
                else
                {
                    using (var preview = await GetPreviewAsync())
                    {
                        return(await ResizeStreamAsync(preview, new Size(maximumSide, maximumSide), orientationValue));
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public async void StopRecord(object sender, RoutedEventArgs e)
        {
            timer.Stop();
            isRecording   = false;
            IsTranslating = true;

            // 停止錄音
            await capture.StopRecordAsync();

            // 轉成 IRandomAccessStream
            IRandomAccessStream audio = buffer.CloneStream();

            // 轉換成文字
            await TranslateAudioToString(audio);

            IsTranslating = false;
        }
        private async void InkPresenter_StrokesCollected(InkPresenter sender, InkStrokesCollectedEventArgs args)
        {
            CanvasDevice       device       = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)inkDataCanvas.ActualWidth, (int)inkDataCanvas.ActualHeight, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Colors.Black);
                ds.DrawInk(inkDataCanvas.InkPresenter.StrokeContainer.GetStrokes());
            }

            using (var ms = new InMemoryRandomAccessStream())
            {
                await renderTarget.SaveAsync(ms, CanvasBitmapFileFormat.Jpeg, 1);

                await ms.FlushAsync();

                var decoder = await BitmapDecoder.CreateAsync(ms);

                var img = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);

                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms);

                encoder.BitmapTransform.ScaledHeight = (uint)ViewModelLocator.Instance.Main.ImageSize;
                encoder.BitmapTransform.ScaledWidth  = (uint)ViewModelLocator.Instance.Main.ImageSize;
                encoder.SetSoftwareBitmap(img);
                await encoder.FlushAsync();

                decoder = await BitmapDecoder.CreateAsync(ms);

                img = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);

                img = SoftwareBitmap.Convert(img, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);

                var sbs = new SoftwareBitmapSource();
                await sbs.SetBitmapAsync(img);

                inkImage.Source = sbs;

                //var targetImage = new SoftwareBitmap(BitmapPixelFormat.Bgra8, img.PixelWidth, img.PixelHeight);
                // img.CopyTo(targetImage);
                ViewModelLocator.Instance.Main.CurrentInkImage = ms.CloneStream();
                ms.Dispose();
            }
        }
Ejemplo n.º 22
0
        public async Task <StorageFile> TrySaveAudio(StorageFolder folder = null)
        {
            try
            {
                if (isRecording)
                {
                    await StopRecording();
                }
                if (playback != null)
                {
                    await StopPlaying();
                }

                if (folder == null)
                {
                    folder = ApplicationData.Current.LocalFolder;
                }

                IRandomAccessStream audio = buffer.CloneStream();
                if (audio == null || audio.Size == 0)
                {
                    return(null);
                }

                var name = UIHelper.GetDateTimeStringForName();
                name.Append(DateTimeOffset.Now.Millisecond);
                string filename = name.Append(audioExtension).ToString();

                StorageFile storageFile = await folder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);

                using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

                    await audio.FlushAsync();

                    audio.Dispose();
                }
                return(storageFile);
            }
            catch
            {
                return(null);
            }
        }
        public ChunkEncodedSocketWrapper(StreamSocket baseSocket, DataReader dataReader, DataWriter dataWriter)
        {
            BaseSocket       = baseSocket;
            SocketDataWriter = dataWriter;

            SetInitialBufferStatus(true); //this should buffer before allowing playback.

            bufferStream = new InMemoryRandomAccessStream();
            bufferTaskCancelTokenSource = new CancellationTokenSource();
            bufferTask = Task.Run(function: ProcessStreamChunksAsync, cancellationToken: bufferTaskCancelTokenSource.Token);

            rawDataReader = dataReader;

            clonedBufferStream = bufferStream.CloneStream();
            SocketDataReader   = new DataReader(clonedBufferStream.GetInputStreamAt(0));

            InitializeDataStream();
        }
Ejemplo n.º 24
0
        private async void SendInk()
        {
            if (!this.isConnect)
            {
                return;
            }
            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();

            await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(randomAccessStream);

            Stream stream = randomAccessStream.CloneStream().AsStream();

            byte[] data = new byte[stream.Length];

            stream.Read(data, 0, (int)stream.Length);

            SendData(data);
        }
Ejemplo n.º 25
0
        public async void StopRecording()
        {
            await _mediaCapture.StopRecordAsync();

            IsRecording = false;
            IRandomAccessStream randomAccessStream = _memoryBuffer.CloneStream();

            Debug.WriteLine(randomAccessStream.Size);
            byte[] arrayByteBuffer = new byte[randomAccessStream.Size];
            await randomAccessStream.ReadAsync(arrayByteBuffer.AsBuffer(), (uint)randomAccessStream.Size, Windows.Storage.Streams.InputStreamOptions.None);

            Debug.WriteLine(BitConverter.ToString(arrayByteBuffer));
            InMemoryRandomAccessStream newStream = new InMemoryRandomAccessStream();
            await newStream.WriteAsync(arrayByteBuffer.AsBuffer());

            SaveAudioToFile(newStream);

            UdpService.Instance.SendMessage(arrayByteBuffer, arrayByteBuffer.Length);
        }
Ejemplo n.º 26
0
        private async void Capture()
        {
            try
            {
                using (var stream = new InMemoryRandomAccessStream())
                {
                    await this.Media.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

                    await stream.FlushAsync();

                    if (this.CapturedCommand != null)
                    {
                        this.CapturedCommand.Execute(stream.CloneStream());
                    }
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 27
0
        public async Task <bool> SaveAudioToFile(string filename = DEFAULT_AUDIO_FILENAME)
        {
            IRandomAccessStream audioStream = _memoryBuffer.CloneStream();
            //StorageFolder storageFolder = Package.Current.InstalledLocation;
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

            StorageFile storageFile = await storageFolder.CreateFileAsync(
                filename, CreationCollisionOption.GenerateUniqueName);

            this._fileName = storageFile.Name;
            using (IRandomAccessStream fileStream =
                       await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(
                    audioStream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

                await audioStream.FlushAsync();

                audioStream.Dispose();
            }
            return(true);
        }
Ejemplo n.º 28
0
        private async Task StopRecording(CoreDispatcher dispatcher)
        {
            try
            {
                StorageFile localStorageFile = null;
                string      path             = string.Empty;

                if (capture != null)
                {
                    await capture.StopRecordAsync();

                    IRandomAccessStream audio = buffer.CloneStream();
                    if (audio == null)
                    {
                        new ArgumentNullException("buffer");
                    }

                    await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                    {
                        localStorageFile = await storageFolder.CreateFileAsync(audioFilename, CreationCollisionOption.GenerateUniqueName);
                        filename         = localStorageFile.Name;
                        path             = localStorageFile.Path;

                        using (IRandomAccessStream fileStream = await localStorageFile.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                            await audio.FlushAsync();
                            audio.Dispose();
                        }

                        running = false;
                    });
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 29
0
        /*
         * 位于项目的 \bin\x86\Debug 目录中
         *
         * */
        private async void SaveToFile(InMemoryRandomAccessStream _memoryBuffer, bool isVideo)
        {
            IRandomAccessStream audioStream   = _memoryBuffer.CloneStream();
            StorageFolder       storageFolder = Package.Current.InstalledLocation;
            string DEFAULT_AUDIO_FILENAME     = "";


            if (isVideo)
            {
                recordFileName  = DateTime.Now.Year.ToString();
                recordFileName += DateTime.Now.Month.ToString();
                recordFileName += DateTime.Now.Day.ToString();

                DEFAULT_AUDIO_FILENAME = recordFileName + ".mp3";
            }
            else
            {
                videoFileName  = DateTime.Now.Year.ToString();
                videoFileName += DateTime.Now.Month.ToString();
                videoFileName += DateTime.Now.Day.ToString();

                DEFAULT_AUDIO_FILENAME = videoFileName + ".mp4";
            }

            StorageFile storageFile = await storageFolder.CreateFileAsync(
                DEFAULT_AUDIO_FILENAME, CreationCollisionOption.GenerateUniqueName);

            using (IRandomAccessStream fileStream =
                       await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(
                    audioStream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

                await audioStream.FlushAsync();

                audioStream.Dispose();
            }
        }
Ejemplo n.º 30
0
        public async Task SaveAudioToFile()
        {
            if (parent != null)
            {
                parent.StartWritingOutputExtended("Writing Audio... please wait...", 0);
            }

            Random random        = new Random();
            int    num           = random.Next(80000) + 10000;
            string audiofilename = "audioFile" + num.ToString() + ".mp3";

            IRandomAccessStream audioStream = memoryAudioStream.CloneStream();
            StorageFolder       tempfolder  = ApplicationData.Current.TemporaryFolder;
            StorageFile         storageFile = await tempfolder.CreateFileAsync(
                audiofilename, CreationCollisionOption.GenerateUniqueName);



            using (IRandomAccessStream fileStream =
                       await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(
                    audioStream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));

                await audioStream.FlushAsync();

                audioStream.Dispose();
            }


            tempAudioFile = storageFile;

            if (parent != null)
            {
                parent.StartWritingOutputExtended("Audio File : " + storageFile.Path, 1);
            }
        }