分类
程序设计

C#在UWP中实现录音功能

我们在开发Windows客户端程序时,有时需要实现录音的功能,比如使用语音识别时。本文中的代码通过DLL导入调用系统API实现了录制16kHz、16bit位宽的单声道wav格式录音。该代码已用于ASRT语音识别客户端SDK(C# UWP版):

https://github.com/nl8590687/ASRT_SpeechClient_UWP

核心类:WavRecorder类实现 (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.ApplicationModel;

namespace ailemon
{
    class AudioRecorder
    {
        private MediaCapture _mediaCapture;
        private InMemoryRandomAccessStream _memoryBuffer;
        public bool IsRecording { get; set; }

        private const string DEFAULT_AUDIO_FILENAME = "1.wav";
        private string _fileName;

        public AudioRecorder()
        {

        }

        public void Initialize()
        {
            _memoryBuffer = new InMemoryRandomAccessStream();
        }

        public async void Record()
        {
            if (IsRecording)
            {
                throw new InvalidOperationException("Recording already in progress!");
            }
            Initialize();
            //await DeleteExistingFile();
            MediaCaptureInitializationSettings settings =
              new MediaCaptureInitializationSettings
              {
                  StreamingCaptureMode = StreamingCaptureMode.Audio
              };
            settings.AudioProcessing = Windows.Media.AudioProcessing.Raw;
            _mediaCapture = new MediaCapture();
            await _mediaCapture.InitializeAsync(settings);

            await _mediaCapture.StartRecordToStreamAsync(
              MediaEncodingProfile.CreateWav(AudioEncodingQuality.Low), _memoryBuffer);

            //MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto)
            IsRecording = true;
        }

        public async void StopRecording()
        {
            if(_mediaCapture != null)
            {
                await _mediaCapture.StopRecordAsync();
                IsRecording = false;
                //SaveAudioToFile();
            }
        }

        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;
        }
        public void Play()
        {
            MediaElement playbackMediaElement = new MediaElement();
            playbackMediaElement.SetSource(_memoryBuffer, "MP3");
            playbackMediaElement.Play();
        }
        public async Task PlayFromDisk(CoreDispatcher dispatcher)
        {
            await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                MediaElement playbackMediaElement = new MediaElement();
                StorageFolder storageFolder = Package.Current.InstalledLocation;
                StorageFile storageFile = await storageFolder.GetFileAsync(this._fileName);
                IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);
                playbackMediaElement.SetSource(stream, storageFile.FileType);
                playbackMediaElement.Play();
            });
        }
        public void Close()
        {
            _mediaCapture.Dispose();
            _memoryBuffer.Dispose();
        }
    }
}

调用样例:

using ailemon; //引用命名空间

AudioRecorder audioRecorder  = new AudioRecorder();//定义并实例化类
audioRecorder.Record(); //录音
audioRecorder.StopRecording(); //停止录音

string filename = "speechfile.wav";
audioRecorder.SaveAudioToFile(filename); //保存录音文件
audioRecorder.Close(); //关闭录音内存流

版权声明
本博客的文章除特别说明外均为原创,本人版权所有。欢迎转载,转载请注明作者及来源链接,谢谢。
本文地址: https://blog.ailemon.net/2020/09/03/csharp-uwp-implement-wav-recorder/
All articles are under Attribution-NonCommercial-ShareAlike 4.0

关注“AI柠檬博客”微信公众号,及时获取你最需要的干货。


发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

4 × 3 =

如果您是第一次在本站发布评论,内容将在博主审核后显示,请耐心等待