将录制的声音保存到UWP中的项目文件

时间:2016-04-14 14:38:07

标签: c# xaml win-universal-app

我用设备的麦克风录制声音,但我不知道如何保存它。它是在MediaCapture元素的帮助下,如果是,那么该怎么做?

1 个答案:

答案 0 :(得分:0)

以下是如何转换为mp3并使用Datawriter保存在文件中的基本知识。

我在运行中编写了这段代码,因此未经过测试。

    MediaEncodingProfile _Profile = Windows.Media.MediaProperties.MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High);
    MediaTranscoder _Transcoder = new Windows.Media.Transcoding.MediaTranscoder();
    CancellationTokenSource _cts = new CancellationTokenSource();

    private void ConvertSteamToMp3()
    {
        IRandomAccessStream audio = buffer.CloneStream(); //your recoreded InMemoryRandomAccessStream

        var folder = KnownFolders.MusicLibrary.CreateFolderAsync("MyCapturedAudio", CreationCollisionOption.OpenIfExists);
        outputFile = await folder.CreateFileAsync("record.mp3", CreationCollisionOption.GenerateUniqueName);

        using (IRandomAccessStream fileStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
        {

            var preparedTranscodeResult = await _Transcoder.PrepareStreamTranscodeAsync(audio, fileStream, _Profile);
            if (preparedTranscodeResult.CanTranscode)
            {
                var progress = new Progress<double>(TranscodeProgress);
                await preparedTranscodeResult.TranscodeAsync().AsTask(_cts.Token, progress);
            }

            using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0))
            {
                using (DataWriter dataWriter = new DataWriter(outputStream))
                {
                    //TODO: Replace "Bytes" with the type you want to write.
                    dataWriter.WriteBytes(bytes);
                    await dataWriter.StoreAsync();
                    dataWriter.DetachStream();
                }

                await outputStream.FlushAsync();
            }
        }
    }

或者只是将流保存在文件中

    public async SaveToFile()
{

    IRandomAccessStream audio = buffer.CloneStream(); //your recoreded InMemoryRandomAccessStream
    var folder  = KnownFolders.MusicLibrary.CreateFolderAsync("MyCapturedAudio", CreationCollisionOption.OpenIfExists);
    outputFile = await folder.CreateFileAsync("record.mp3", CreationCollisionOption.GenerateUniqueName);

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