示例#1
0
        private void buttonLoadBinaryData_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            picker.FileTypeFilter.Add(".bin");
            var dispatcher = this.Dispatcher;

            ((Action)(async() =>
            {
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async() =>
                {
                    var file = await picker.PickSingleFileAsync();
                    if (file == null)
                    {
                        return;
                    }
                    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                    var reader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0));
                    var count = await reader.LoadAsync((uint)stream.Size);
                    var buffer = reader.ReadBuffer(count);
                    var str = Util.BinaryBufferToBinaryString(buffer);

                    var index = (sender as Windows.UI.Xaml.Controls.Control).Name.Replace("buttonLoadBinaryData", "");
                    TextBox textBox = Util.FindControl(Input, "textBoxBinaryData" + index) as TextBox;
                    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() =>
                    {
                        textBox.Text = str;
                        textBox.SetValue(RawBinaryDataProperty, buffer);
                    }));
                }));
            }
                      )).Invoke();
        }
示例#2
0
        public static async System.Threading.Tasks.Task <int> SynSpeechWriteToFileAsync(string text, string fileName)
        {
            using (Windows.Media.SpeechSynthesis.SpeechSynthesizer synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer())
            {
                try
                {
                    using (Windows.Media.SpeechSynthesis.SpeechSynthesisStream synthStream = await synth.SynthesizeTextToStreamAsyncServiceAsync(text, apiArgs)) // doesn't handle special characters such as quotes
                    {
                        // TODO: obsolete to use DataReader? use await Windows.Storage.FileIO.Read...(file);
                        using (Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(synthStream))
                        {
                            await reader.LoadAsync((uint)synthStream.Size);

                            Windows.Storage.Streams.IBuffer buffer     = reader.ReadBuffer((uint)synthStream.Size);
                            Windows.Storage.StorageFolder   tempFolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(Options.options.tempFolderPath);

                            Windows.Storage.StorageFile srcFile = await tempFolder.CreateFileAsync(Options.options.audio.speechSynthesisFileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                            await Windows.Storage.FileIO.WriteBufferAsync(srcFile, buffer);

                            Windows.Storage.FileProperties.MusicProperties musicProperties = await srcFile.Properties.GetMusicPropertiesAsync();

                            Log.WriteLine("Bitrate:" + musicProperties.Bitrate);

                            Windows.Media.MediaProperties.MediaEncodingProfile profile    = Windows.Media.MediaProperties.MediaEncodingProfile.CreateWav(Windows.Media.MediaProperties.AudioEncodingQuality.Low);
                            Windows.Media.Transcoding.MediaTranscoder          transcoder = new Windows.Media.Transcoding.MediaTranscoder();
                            Windows.Storage.StorageFile destFile = await tempFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                            Windows.Media.Transcoding.PrepareTranscodeResult result = await transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile);

                            if (result.CanTranscode)
                            {
                                await result.TranscodeAsync();
                            }
                            else
                            {
                                Log.WriteLine("can't transcode file:" + result.FailureReason.ToString());
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return(0);
        }
示例#3
0
        private async Task <Stream> ReadFile(string filename)
        {
            var file = await Folder.GetFileAsync(filename);

            if (!file.IsAvailable)
            {
                this.UpdateCache().ConfigureAwait(false);
                return(null);
            }
            var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

            var inStream = fs.GetInputStreamAt(0);
            var reader   = new Windows.Storage.Streams.DataReader(inStream);
            await reader.LoadAsync((uint)fs.Size);

            var data = reader.ReadBuffer((uint)fs.Size);

            reader.DetachStream();
            return(data.AsStream());
        }
            /// <summary>
            /// This is an internal method called from ReadInternal method.
            /// </summary>
            /// <param name="buffer">The byte array, passed to Read method.</param>
            /// <param name="offset">The offset in the buffer array to begin writing.</param>
            /// <param name="count">The number of bytes to read.</param>
            /// <param name="timeout">Milliseconds before a time-out occurs.</param>
            /// <param name="ct">A cancellation_token will be signaled by user cancellation.</param>
            /// <returns>
            /// The result of Task contains the length of bytes read. This may be less than count.
            /// </returns>
            private Task<int> ReadPartial(
                Windows.Storage.Streams.IBuffer buffer, 
                int offset, 
                int count,
                int timeout,
                System.Threading.CancellationToken ct
            )
            {
                // Buffer check.
                if ((int)buffer.Length < (offset + count))
                {
                    throw new ArgumentException("Capacity of buffer is not enough.");
                }

                var inputStream = this.cdcData.BulkInPipes[0].InputStream;
                var reader = new Windows.Storage.Streams.DataReader(inputStream);

                return Task.Run(async () =>
                {
                    // CancellationTokenSource to cancel tasks.
                    var cancellationTokenSource = new System.Threading.CancellationTokenSource();

                    // LoadAsync task.
                    var loadTask = reader.LoadAsync((uint)count).AsTask<uint>(cancellationTokenSource.Token);

                    // A timeout task that completes after the specified delay.
                    var timeoutTask = Task.Delay(timeout == Constants.InfiniteTimeout ? System.Threading.Timeout.Infinite : timeout, cancellationTokenSource.Token);

                    // Cancel tasks by user's cancellation.
                    bool canceledByUser = false;
                    ct.Register(()=>
                    {
                        canceledByUser = true;
                        cancellationTokenSource.Cancel();
                    });

                    // Wait tasks.
                    Task[] tasks = { loadTask, timeoutTask };
                    var signaledTask = await Task.WhenAny(tasks);

                    // Check the task status.
                    bool loadCompleted = signaledTask.Equals(loadTask) && loadTask.IsCompleted && !loadTask.IsCanceled;
                    bool isTimeout = signaledTask.Equals(timeoutTask) && timeoutTask.IsCompleted && !timeoutTask.IsCanceled;

                    // Cancel all incomplete tasks.
                    cancellationTokenSource.Cancel();

                    int loadedCount = 0;
                    if (loadCompleted)
                    {
                        loadedCount = (int)loadTask.Result;
                    }
                    else if (isTimeout)
                    {
                        // Timeout.
                        throw new System.TimeoutException("ReadPartial was timeout.");
                    }
                    else if (canceledByUser)
                    {
                        throw new OperationCanceledException("ReadPartial was canceled.");
                    }

                    if (loadedCount > 0)
                    {
                        var readBuffer = reader.ReadBuffer((uint)loadedCount);
                        System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.CopyTo(readBuffer, 0, buffer, (uint)offset, (uint)loadedCount);
                    }

                    return loadedCount;
                });
            }
            /// <summary>
            /// This is an internal method called from ReadInternal method.
            /// </summary>
            /// <param name="buffer">The byte array, passed to Read method.</param>
            /// <param name="offset">The offset in the buffer array to begin writing.</param>
            /// <param name="count">The number of bytes to read.</param>
            /// <param name="timeout">Milliseconds before a time-out occurs.</param>
            /// <param name="ct">A cancellation_token will be signaled by user cancellation.</param>
            /// <returns>
            /// The result of Task contains the length of bytes read. This may be less than count.
            /// </returns>
            private Task <int> ReadPartial(
                Windows.Storage.Streams.IBuffer buffer,
                int offset,
                int count,
                int timeout,
                System.Threading.CancellationToken ct
                )
            {
                // Buffer check.
                if ((int)buffer.Length < (offset + count))
                {
                    throw new ArgumentException("Capacity of buffer is not enough.");
                }

                var inputStream = this.cdcData.BulkInPipes[0].InputStream;
                var reader      = new Windows.Storage.Streams.DataReader(inputStream);

                return(Task.Run(async() =>
                {
                    // CancellationTokenSource to cancel tasks.
                    var cancellationTokenSource = new System.Threading.CancellationTokenSource();

                    // LoadAsync task.
                    var loadTask = reader.LoadAsync((uint)count).AsTask <uint>(cancellationTokenSource.Token);

                    // A timeout task that completes after the specified delay.
                    var timeoutTask = Task.Delay(timeout == Constants.InfiniteTimeout ? System.Threading.Timeout.Infinite : timeout, cancellationTokenSource.Token);

                    // Cancel tasks by user's cancellation.
                    bool canceledByUser = false;
                    ct.Register(() =>
                    {
                        canceledByUser = true;
                        cancellationTokenSource.Cancel();
                    });

                    // Wait tasks.
                    Task[] tasks = { loadTask, timeoutTask };
                    var signaledTask = await Task.WhenAny(tasks);

                    // Check the task status.
                    bool loadCompleted = signaledTask.Equals(loadTask) && loadTask.IsCompleted && !loadTask.IsCanceled;
                    bool isTimeout = signaledTask.Equals(timeoutTask) && timeoutTask.IsCompleted && !timeoutTask.IsCanceled;

                    // Cancel all incomplete tasks.
                    cancellationTokenSource.Cancel();

                    int loadedCount = 0;
                    if (loadCompleted)
                    {
                        loadedCount = (int)loadTask.Result;
                    }
                    else if (isTimeout)
                    {
                        // Timeout.
                        throw new System.TimeoutException("ReadPartial was timeout.");
                    }
                    else if (canceledByUser)
                    {
                        throw new OperationCanceledException("ReadPartial was canceled.");
                    }

                    if (loadedCount > 0)
                    {
                        var readBuffer = reader.ReadBuffer((uint)loadedCount);
                        System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.CopyTo(readBuffer, 0, buffer, (uint)offset, (uint)loadedCount);
                    }

                    return loadedCount;
                }));
            }
        private void buttonLoadBinaryData_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            picker.FileTypeFilter.Add(".bin");
            var dispatcher = this.Dispatcher;
            ((Action)(async () =>
            {
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () =>
                {
                    var file = await picker.PickSingleFileAsync();
                    if (file == null)
                    {
                        return;
                    }
                    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                    var reader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0));
                    var count = await reader.LoadAsync((uint)stream.Size);
                    var buffer = reader.ReadBuffer(count);
                    var str = Util.BinaryBufferToBinaryString(buffer);

                    var index = (sender as Windows.UI.Xaml.Controls.Control).Name.Replace("buttonLoadBinaryData", "");
                    TextBox textBox = Util.FindControl(Input, "textBoxBinaryData" + index) as TextBox;
                    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() =>
                    {
                        textBox.Text = str;
                        textBox.SetValue(RawBinaryDataProperty, buffer);
                    }));
                }));
            }
            )).Invoke();
        }