コード例 #1
0
ファイル: SaveLoad.cs プロジェクト: Kulu-M/Universal-Apps
        public static async Task <T> readObjektAsync <T>(string datei)
        {
            StorageFile         file;
            IRandomAccessStream inStream = null;

            try
            {
                file = await ApplicationData.Current.LocalFolder.GetFileAsync(datei);

                inStream = await file.OpenAsync(FileAccessMode.Read);

                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                var data = (T)serializer.ReadObject(inStream.AsStreamForRead());
                inStream.Dispose();

                return(data);
            }
            catch (Exception)
            {
                if (inStream != null)
                {
                    inStream.Dispose();
                }
                return(default(T));
            }
        }
コード例 #2
0
        static async void GetMission()
        {
            StorageFile ss = await rsf.CreateFileAsync("info", CreationCollisionOption.OpenIfExists);

            if (ss != null)
            {
                try
                {
                    IRandomAccessStream i = await ss.OpenAsync(FileAccessMode.ReadWrite);

                    if (i.Size == 0)
                    {
                        i.Dispose();
                        return;
                    }
                    DataReader dr = new DataReader(i);
                    await dr.LoadAsync((uint)i.Size);

                    byte[] buff = new byte[i.Size];
                    dr.ReadBytes(buff);
                    dr.Dispose();
                    i.Dispose();
                    ReadMission(ref buff);
                }
                catch (Exception ex)
                {
                    Main.Notify(ex.Message);
                }
            }
        }
コード例 #3
0
        private async void OnCapturePhotoCompleted(IRandomAccessStream stream, IAsyncAction result, AsyncStatus status)
        {
            try
            {
                Stream streamCopy = stream.AsStreamForRead();
                streamCopy.Position = 0;
                Face[] faces = await _faceClient.DetectAsync(streamCopy);

                stream.Dispose();
                stream = null;
                bool userDetected = false;
                foreach (var face in faces)
                {
                    VerifyResult verifyResult = await _faceClient.VerifyAsync(face.FaceId, _groupId, _personId);

                    if (userDetected = verifyResult.IsIdentical)
                    {
                        break;
                    }
                }
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    if (userDetected && !_loggedOn)
                    {
                        txtGreeting.Text = "Hello!";
                        animGreeting.Begin();
                        _loggedOn                     = true;
                        imgLogoff.Visibility          = Windows.UI.Xaml.Visibility.Collapsed;
                        imgLogon.Visibility           = Windows.UI.Xaml.Visibility.Visible;
                        itmsCalendarEvents.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    }
                    else if (!userDetected && _loggedOn)
                    {
                        txtGreeting.Text = "Goodbye!";
                        animGreeting.Begin();
                        _loggedOn                     = false;
                        imgLogoff.Visibility          = Windows.UI.Xaml.Visibility.Visible;
                        imgLogon.Visibility           = Windows.UI.Xaml.Visibility.Collapsed;
                        itmsCalendarEvents.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    }
                });
            }
            catch (FaceAPIException e)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    txtException.Text = e.ErrorMessage;
                    animException.Begin();
                });
            }
            catch (Exception)
            {
                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }
            }
        }
コード例 #4
0
        private async void AcceptButton_Click(object sender, RoutedEventArgs e)
        {
            Pause();

            progressText.Text        = "0";
            progressText.Visibility  = Visibility.Visible;
            completedText.Visibility = Visibility.Collapsed;

            overlayGrid.Visibility = Visibility.Visible;
            OpenProcessingOverlay.Begin();

            Analytics.TrackEvent("VideoEditor_ExportStarted");

            await SaveComposition();

            var transcoder = new MediaTranscoder()
            {
                VideoProcessingAlgorithm = App.RoamingSettings.Read(Constants.VIDEO_PROCESSING, MediaVideoProcessingAlgorithm.Default)
            };
            var props   = await(_model.StorageFile as StorageFile).Properties.GetVideoPropertiesAsync();
            var profile = MediaTranscoding.CreateVideoEncodingProfileFromProps(props);
            var source  = _model.Composition.GenerateMediaStreamSource();

            if (_tempFile == null)
            {
                _tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(Path.ChangeExtension(_model.StorageFile.Name, ".mp4"), CreationCollisionOption.GenerateUniqueName);
            }

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

            _tempStream = await _tempFile.OpenAsync(FileAccessMode.ReadWrite);

            var result = await transcoder.PrepareMediaStreamSourceTranscodeAsync(source, _tempStream, profile);

            if (!result.CanTranscode)
            {
                await UIUtilities.ShowErrorDialogAsync("Unable to Transcode!", $"Returned {result.FailureReason}");

                return;
            }

            _renderTask            = result.TranscodeAsync();
            _renderTask.Progress   = OnProgress;
            _renderTask.Completed += OnCompleted;
        }
コード例 #5
0
        public static async void LoadData()
        {
            actionList.Clear();
            try
            {
                StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("actionList.dat");

                IRandomAccessStream raStream = await storageFile.OpenAsync(FileAccessMode.Read);

                DataReader reader = new DataReader(raStream);
                reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                reader.ByteOrder       = ByteOrder.LittleEndian;

                await reader.LoadAsync((uint)raStream.Size);

                int dataLength = reader.ReadInt32();
                for (int i = 0; i < dataLength; i++)
                {
                    Kinect.Joint[] action = new Kinect.Joint[20];
                    for (int j = 0; j < 20; j++)
                    {
                        Kinect.Joint joint = new Kinect.Joint();
                        joint.JointType = (Kinect.JointType)reader.ReadByte();
                        joint.X         = reader.ReadSingle();
                        joint.Y         = reader.ReadSingle();
                        joint.Z         = reader.ReadSingle();
                        action[j]       = joint;
                    }
                    actionList.Add(action);
                }
                raStream.Dispose();
            }
            catch { }
        }
コード例 #6
0
ファイル: DataLoader.partial.cs プロジェクト: Valentine1/LG
        async private Task Save(XDocument xdoc, string path)
        {
            StringWriter swriter = new StringWriter();

            xdoc.Save(swriter, SaveOptions.None);
            string  xmlString          = swriter.GetStringBuilder().ToString();
            IBuffer xmlEncryptedBuffer = EncryptionProvider.Encrypt(xmlString);

            StorageFolder sf = await ApplicationData.Current.LocalFolder.GetFolderAsync(@"data\");

            var file = await sf.GetFileAsync(Path.GetFileName(path));

            using (IRandomAccessStream ras = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outs = ras.GetOutputStreamAt(0))
                {
                    await outs.WriteAsync(xmlEncryptedBuffer);

                    bool suc = await outs.FlushAsync();

                    outs.Dispose();
                }
                ras.Dispose();
            }
        }
コード例 #7
0
        private async void RenderInkImageAsync()
        {
            IReadOnlyList <InkStroke> currentStrokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();

            if (currentStrokes.Count > 0)
            {
                Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.TemporaryFolder;
                Windows.Storage.StorageFile   file          = await storageFolder.CreateFileAsync($"{Guid.NewGuid()}.png", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                if (file != null)
                {
                    Windows.Storage.CachedFileManager.DeferUpdates(file);

                    IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                    using (IOutputStream outputStream = stream.GetOutputStreamAt(0))
                    {
                        await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);

                        await outputStream.FlushAsync();
                    }
                    stream.Dispose();
                }

                BitmapImage bm = new BitmapImage(new Uri($"ms-appdata:///temp/{file.Name}"));

                App.ViewModel.SelectedDocument.AnnotationImage = bm;
            }

            Frame.GoBack();
        }
コード例 #8
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();
            });
        }
コード例 #9
0
ファイル: DataRecorder.cs プロジェクト: gaviral/Holobrain
    private void OnDestroy()
    {
#if WINDOWS_UWP
        stream.Dispose();
        recordingData = false;
#endif
    }
コード例 #10
0
        private async void BtnOpen_Click(object sender, RoutedEventArgs e)
        {
            InkStrokeContainer container = new InkStrokeContainer();

            Windows.Storage.Pickers.FileOpenPicker openPicker = new Windows.Storage.Pickers.FileOpenPicker();
            openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add(".gif");

            Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                using (var inputStream = stream.GetInputStreamAt(0))
                {
                    await container.LoadAsync(inputStream);
                }
                stream.Dispose();
                _inkStrokes.Clear();

                _inkStrokes.Add(container);
                DrawingCanvas.Invalidate();
            }


            else
            {
            }
        }
コード例 #11
0
ファイル: SaveLoad.cs プロジェクト: Kulu-M/Universal-Apps
        public static async Task <bool> writeObjektAsync <T>(string file, T objekt)
        {
            try
            {
                StorageFile userdetailsfile = await
                                              ApplicationData.Current.LocalFolder.CreateFileAsync(file, CreationCollisionOption.ReplaceExisting);

                IRandomAccessStream rndStream = await
                                                userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);

                using (IOutputStream outStream = rndStream.GetOutputStreamAt(0))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    serializer.WriteObject(outStream.AsStreamForWrite(), objekt);
                    var xx = await outStream.FlushAsync();

                    rndStream.Dispose();
                    outStream.Dispose();
                }
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
コード例 #12
0
        private static async Task <string> SaveFileAsync(RenderTargetBitmap image, string fileName, uint imageWidth, uint imageHeight)
        {
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                var pixelsBuffer = await image.GetPixelsAsync();

                byte[] bytes = pixelsBuffer.ToArray();

                var dpi = DisplayInformation.GetForCurrentView().LogicalDpi;

                encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                     BitmapAlphaMode.Straight,
                                     (uint)image.PixelWidth, (uint)image.PixelHeight,
                                     dpi, dpi, bytes);

                await encoder.FlushAsync();

                stream.Dispose();
            }

            return(file.Name);
        }
コード例 #13
0
        private async void openBtn_Click(object sender, RoutedEventArgs e)
        {
            // Let users choose their ink file using a file picker.
            // Initialize the picker.
            Windows.Storage.Pickers.FileOpenPicker openPicker =
                new Windows.Storage.Pickers.FileOpenPicker();
            openPicker.SuggestedStartLocation =
                Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".png");
            // Show the file picker.
            Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();

            // User selects a file and picker returns a reference to the selected file.
            if (file != null)
            {
                // Open a file stream for reading.
                IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                // Read from file.
                using (var inputStream = stream.GetInputStreamAt(0))
                {
                    await myCanvas.InkPresenter.StrokeContainer.LoadAsync(inputStream);
                }
                stream.Dispose();
            }
            // User selects Cancel and picker returns null.
            else
            {
                // Operation cancelled.
            }
        }
コード例 #14
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();
            });
        }
コード例 #15
0
        private async void GoRun()
        {
            RenderTargetBitmap bmp = new RenderTargetBitmap();
            await bmp.RenderAsync(GridEmoji);

            IBuffer buffer = await bmp.GetPixelsAsync();

            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";

            StorageFolder savedPics = KnownFolders.SavedPictures;
            // 创建新文件
            StorageFile newFile = await savedPics.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            // 获取文件流
            IRandomAccessStream streamOut = await newFile.OpenAsync(FileAccessMode.ReadWrite);

            // 实例化编码器
            BitmapEncoder pngEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, streamOut);

            // 写入像素数据
            byte[] data = buffer.ToArray();
            pngEncoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                    BitmapAlphaMode.Straight,
                                    (uint)bmp.PixelWidth,
                                    (uint)bmp.PixelHeight,
                                    96d, 96d, data);
            await pngEncoder.FlushAsync();

            streamOut.Dispose();
        }
コード例 #16
0
        public static async Task PlayStreamAsync(this MediaElement mediaElement, IRandomAccessStream stream, bool disposeStream = true)
        {
            // bool is irrelevant here, just using this to flag task completion.
            TaskCompletionSource<bool> taskCompleted = new TaskCompletionSource<bool>();

            // Note that the MediaElement needs to be in the UI tree for events like MediaEnded to fire.
            RoutedEventHandler endOfPlayHandler = (s, e) =>
            {
                if (disposeStream)
                    stream.Dispose();

                taskCompleted.SetResult(true);
            };

            mediaElement.MediaEnded += endOfPlayHandler;

            mediaElement.SetSource(stream, (stream as SpeechSynthesisStream).ContentType);
            mediaElement.Volume = 1;
            mediaElement.IsMuted = false;
            mediaElement.Play();

            await taskCompleted.Task;

            mediaElement.MediaEnded -= endOfPlayHandler;
        }
コード例 #17
0
ファイル: SleepingScreen.xaml.cs プロジェクト: dumbie/TimeMe
        //Set sleepingscreen wallpaper
        async Task UpdateWallpaper()
        {
            try
            {
                if ((bool)vApplicationSettings["ScreenWallpaper"] && await AVFunctions.LocalFileExists("TimeMeTilePhoto.png"))
                {
                    StorageFile StorageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("TimeMeTilePhoto.png");

                    using (IRandomAccessStream OpenAsync = await StorageFile.OpenAsync(FileAccessMode.Read))
                    {
                        BitmapImage BitmapImage = new BitmapImage();
                        await BitmapImage.SetSourceAsync(OpenAsync);

                        OpenAsync.Dispose();
                        grid_Sleepwallpaper.Background = new ImageBrush()
                        {
                            ImageSource = new Image()
                            {
                                Source = BitmapImage
                            }.Source, Opacity = ((float)Convert.ToInt32(vApplicationSettings["DisplayBackgroundBrightness"]) / 100), Stretch = Stretch.UniformToFill, AlignmentY = AlignmentY.Center, AlignmentX = AlignmentX.Center
                        };
                    }
                }
            }
            catch { }
        }
コード例 #18
0
        private async void StoreImage(WriteableBitmap bmp, SpriteTextureType spriteTextureType)
        {
            if (!EnableImageStoring)
            {
                return;
            }
            var folderDesc = await FolderOfType(spriteTextureType);

            IRandomAccessStream stream = null;

            DeleteFilesUntilIndex(folderDesc.folder, folderDesc.lastIndex);
            try
            {
                folderDesc.lastIndex++;
                var file = await folderDesc.folder.CreateFileAsync(folderDesc.lastIndex.ToString());

                stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                if (stream.CanWrite)
                {
                    await bmp.WriteBinAsync(stream);

                    await stream.FlushAsync();

                    stream.Dispose();
                    stream = null;
                    return;
                }
            }
            catch
            {
            }
        }
コード例 #19
0
        public static async Task <SoftwareBitmapSource> ThumbnailProcess(StorageFile inputFile)
        {
            const uint             requestedSize    = 300;
            const ThumbnailMode    thumbnailMode    = ThumbnailMode.SingleItem;
            const ThumbnailOptions thumbnailOptions = ThumbnailOptions.ResizeThumbnail;
            var thumbnail = await inputFile.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions);

            var            source = new SoftwareBitmapSource();
            SoftwareBitmap softwareBitmap;

            using (IRandomAccessStream stream = thumbnail)
            {
                // Create the decoder from the stream
                var decoder = await BitmapDecoder.CreateAsync(stream);

                // Get the SoftwareBitmap representation of the file
                softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                decoder = null;
                stream.Dispose();
            }
            if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 ||
                softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
            {
                softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
            }

            await source.SetBitmapAsync(softwareBitmap);

            thumbnail.Dispose();//如果有机器慢的话就删除这句
            // softwareBitmap.Dispose();//造成不能实现UI虚拟化的元凶,代价是增加内存
            return(source);
        }
コード例 #20
0
        private async void LoadPdfFileAsync(StorageFile bookUrl)
        {
            try
            {
                ObservableCollection <BookPdf> bookPages = new ObservableCollection <BookPdf>();
                PdfDocument pdfDocument = await PdfDocument.LoadFromFileAsync(bookUrl);

                int count = 0;
                popUp.IsOpen           = true;
                progressLoader.Maximum = (int)pdfDocument.PageCount;
                pageCount.Text         = pdfDocument.PageCount.ToString() + " Pages";
                progressStatus.Text    = "Loading Pages...";
                for (int pageIndex = 0; pageIndex < pdfDocument.PageCount; pageIndex++)
                {
                    var pdfPage = pdfDocument.GetPage((uint)pageIndex);
                    if (pdfPage != null)
                    {
                        StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
                        StorageFile   pngFile    = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting);

                        if (pngFile != null && pdfPage != null)
                        {
                            IRandomAccessStream randomStream = await pngFile.OpenAsync(FileAccessMode.ReadWrite);

                            await pdfPage.RenderToStreamAsync(randomStream);

                            await randomStream.FlushAsync();

                            randomStream.Dispose();
                            pdfPage.Dispose();


                            count++;
                            progressLoader.Value = pageIndex;
                            int progress = (100 * pageIndex) / (int)pdfDocument.PageCount;

                            downloadSize.Text = String.Format("{0} of {1} pages loaded - {2} % complete.", pageIndex, pdfDocument.PageCount, progress);
                            bookPages.Add(new BookPdf {
                                Id = pageIndex.ToString(), PageNumber = pageIndex.ToString(), ImagePath = pngFile.Path
                            });
                        }
                    }
                }

                if (progressLoader.Value >= 99 || count >= (int)pdfDocument.PageCount - 1)
                {
                    progressStatus.Text = "Pages Loaded";
                    popUp.IsOpen        = false;
                }
                bookPagesView.ItemsSource = bookPages;
            }
            catch (Exception ex)
            {
                var popup = new Windows.UI.Popups.MessageDialog("Cant load the file. The program might have failed to open the file  or you are not connected");
                popup.Commands.Add(new Windows.UI.Popups.UICommand("Ok"));
                popup.DefaultCommandIndex = 0;
                popup.CancelCommandIndex  = 1;
                var results = await popup.ShowAsync();
            }
        }
コード例 #21
0
        public static async Task PlayStreamAsync(
            this MediaElement mediaElement,
            IRandomAccessStream stream,
            bool disposeStream = true)
        {
            // bool is irrelevant here, just using this to flag task completion.
            TaskCompletionSource <bool> taskCompleted = new TaskCompletionSource <bool>();

            // Note that the MediaElement needs to be in the UI tree for events
            // like MediaEnded to fire.
            RoutedEventHandler endOfPlayHandler = (s, e) =>
            {
                if (disposeStream)
                {
                    stream.Dispose();
                }
                taskCompleted.SetResult(true);
            };

            mediaElement.MediaEnded += endOfPlayHandler;

            mediaElement.SetSource(stream, string.Empty);
            mediaElement.Play();

            await taskCompleted.Task;

            mediaElement.MediaEnded -= endOfPlayHandler;
        }
コード例 #22
0
        private async void buttonLoad_ClickAsync(object sender, RoutedEventArgs e)
        {
            // Use a file picker to identify ink file.
            Windows.Storage.Pickers.FileOpenPicker openPicker =
                new Windows.Storage.Pickers.FileOpenPicker();
            openPicker.SuggestedStartLocation =
                Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add(".gif");
            // Show the file picker.
            Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();

            // When selected, picker returns a reference to the file.
            if (file != null)
            {
                // Open a file stream for reading.
                IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                // Read from file.
                using (var inputStream = stream.GetInputStreamAt(0))
                {
                    await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(inputStream);
                }
                stream.Dispose();
            }
            // User selects Cancel and picker returns null.
            else
            {
                // Operation cancelled.
            }
        }
コード例 #23
0
        protected async Task <string> SaveBitmapFile(WriteableBitmap wb)
        {
            EventSource.Log.Debug("SaveBitmapFile()");

            // Copy our current color image
            DateTime now      = DateTime.Now;
            string   fileName = "KinectPhotobooth" + "-" + now.ToString("s").Replace(":", "-") + "-" + now.Millisecond.ToString() + ".png";

            StorageFile file = await this.targetFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

            IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);

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

            Stream pixelStream = wb.PixelBuffer.AsStream();

            byte[] pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)wb.PixelWidth, (uint)wb.PixelHeight, 96.0, 96.0, pixels);

            // clean up
            pixelStream.Dispose();
            await encoder.FlushAsync();

            await stream.FlushAsync();

            stream.Dispose();

            return(fileName);
        }
コード例 #24
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();
        });
    }
コード例 #25
0
ファイル: AudioRecorder.cs プロジェクト: ploiu/Bob
 public void DisposeStream()
 {
     if (stream != null)
     {
         stream.Dispose();
     }
 }
コード例 #26
0
ファイル: AudioRecorder.cs プロジェクト: ploiu/Bob
        /// <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 = this.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();
            }
            this.DisposeMemoryBuffer();

            return(this._fileName);
        }
コード例 #27
0
ファイル: InkPage.cs プロジェクト: vatsal22/Notebook
        public async Task loadAsync()
        {
            string file_name = _pageID.ToString() + page_file_name;

            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   file          = await storageFolder.GetFileAsync(file_name);


            // When selected, picker returns a reference to the file.
            if (file != null)
            {
                // Open a file stream for reading.
                IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                // Read from file.
                using (var inputStream = stream.GetInputStreamAt(0))
                {
                    await GetInkCanvas().InkPresenter.StrokeContainer.LoadAsync(inputStream);
                }
                stream.Dispose();
            }
            // User selects Cancel and picker returns null.
            else
            {
                // must be empty,
            }
        }
コード例 #28
0
ファイル: WaveFile.cs プロジェクト: yutoosakana/K4W2-Book
        // Protected implementation of Dispose pattern.
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                // Free any other managed objects here.
                //

                if (binaryWriter != null)
                {
                    WriteWaveHeader(dataSize);
                    binaryWriter.Dispose();
                    binaryWriter = null;

                    stream.Dispose();
                }
            }

            // Free any unmanaged objects here.
            //
            disposed = true;
        }
コード例 #29
0
        private async Task <Uri> SaveImageAsync(WriteableBitmap writableBitmap, string key)
        {
            //var uri =  await _fileStorageService.CreateFileAsync(key, "png");

            var storageFile = (StorageFile)await _fileStorageService.GetFileObjectAsync(key);

            IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);

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

            // Get pixels of the WriteableBitmap object
            Stream pixelStream = writableBitmap.PixelBuffer.AsStream();

            byte[] pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);

            encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                 BitmapAlphaMode.Straight,
                                 (uint)writableBitmap.PixelWidth,
                                 (uint)writableBitmap.PixelHeight,
                                 96.0,
                                 96.0,
                                 pixels);
            await encoder.FlushAsync();

            stream.Dispose();
            pixelStream.Dispose();

            return(_fileStorageService.GetUriFromFile(storageFile));
        }
コード例 #30
0
        public static async Task <AccountInfo> LoadPersonalDataFromJson()
        {
            if (personalTextFile == null)
            {
                personalTextFile = await StorageFolder.CreateFileAsync(PersonalDataFileName, CreationCollisionOption.ReplaceExisting);
            }

            using (IRandomAccessStream textStream = await personalTextFile.OpenReadAsync())
            {
                using (DataReader textReader = new DataReader(textStream))
                {
                    //get size              s
                    uint textLength = (uint)textStream.Size;
                    await textReader.LoadAsync(textLength);

                    // read it
                    string jsonContents = textReader.ReadString(textLength);
                    // deserialize back to our product!
                    List <userData>    userList          = JsonConvert.DeserializeObject <List <userData> >(jsonContents);
                    List <AccountInfo> convertedUserList = UserdataToUser(userList);


                    AccountInfo accountInfoFromJsonFile = convertedUserList[0];
                    // and show it
                    textStream.Dispose();
                    return(accountInfoFromJsonFile);
                }
            }
        }
コード例 #31
0
ファイル: VoiceNote.cs プロジェクト: PhilipBoyle/PBVoiceNote
    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();
        });
    }
コード例 #32
0
        private async void OnLoadImage(IRandomAccessStream imageStream)
        {
            var image = new WriteableBitmap(1, 1);

            image.SetSource(imageStream);

            ComicImage.Source = image;

            ComicImage.Width = 400;
            ComicImage.Height = 300;

            imageStream.Dispose();
        }
コード例 #33
0
        private async Task Play(IRandomAccessStream buffer)
        {
            if (buffer == null)
                throw new ArgumentNullException("buffer");

            var storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            if (!string.IsNullOrEmpty(_fileName))
            {
                var oldFile = await storageFolder.GetFileAsync(_fileName);
                await oldFile.DeleteAsync();
            }

            await Dispatcher.RunAsync(
                CoreDispatcherPriority.Normal,
                async () =>
                {
                    var storageFile = await storageFolder.CreateFileAsync(AudioFileName, CreationCollisionOption.GenerateUniqueName);

                    _fileName = storageFile.Name;

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

                        await buffer.FlushAsync();
                        buffer.Dispose();
                    }

                    var stream = await storageFile.OpenAsync(FileAccessMode.Read);
                    playBack.SetSource(stream, storageFile.FileType);

                    playBack.Play();
                });
        }