我用来学习如何录制和播放音频的使用捕获设备的媒体捕获示例实际上对我有用。
事实证明,项目没有为我构建的原因是因为一个不相关的 VS2013 错误,我按照在线说明修复了该错误(细节与此讨论无关)。
要回答我自己的问题,“MediaCapture”类是正确使用的类。需要注意的一点是,此类是新多媒体API 的一部分,该 API 可与 Windows 8.1 上的 Windows Store 应用程序和 Windows Phone 8.1 一起使用。
由于目前还没有大量的代码示例,我将分享我自己在 WP8.1 上录制和播放音频的粗略代码。这段代码被简化为基础,这里没有真正的错误处理或任何东西。在前端 (XAML),我只有两个带有 OnClick 事件的按钮,用于开始和停止录音。
这是我的全局变量:
private MediaCapture _mediaCaptureManager;
private StorageFile _recordStorageFile;
private bool _recording;
private bool _suspended;
private bool _userRequestedRaw;
private bool _rawAudioSupported;
private TypedEventHandler
<SystemMediaTransportControls, SystemMediaTransportControlsPropertyChangedEventArgs> _mediaPropertyChanged;
为了初始化设备以录制音频,我在应用程序初始化时使用了这种方法:
private async void InitializeAudioRecording()
{
_mediaCaptureManager = new MediaCapture();
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
settings.MediaCategory = MediaCategory.Other;
settings.AudioProcessing = (_rawAudioSupported && _userRequestedRaw) ? AudioProcessing.Raw : AudioProcessing.Default;
await _mediaCaptureManager.InitializeAsync(settings);
Debug.WriteLine("Device initialised successfully");
_mediaCaptureManager.RecordLimitationExceeded += new RecordLimitationExceededEventHandler(RecordLimitationExceeded);
_mediaCaptureManager.Failed += new MediaCaptureFailedEventHandler(Failed);
}
在 UI 上发生点击事件后,我调用此代码开始录音:
private async void CaptureAudio()
{
try
{
Debug.WriteLine("Starting record");
String fileName = AUDIO_FILE_NAME;
_recordStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
Debug.WriteLine("Create record file successfully");
MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Auto);
await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, this._recordStorageFile);
Debug.WriteLine("Start Record successful");
}
catch(Exception e)
{
Debug.WriteLine("Failed to capture audio");
}
}
这利用了 .NET 4.5 的新await 和 async特性,因此初始化和开始录制以及停止和回放录制的调用是异步的,因此 UI 不会被阻塞,因此我们可以继续在此期间执行其他任务。
在单独的单击事件停止录制时,我调用此代码,它将录音保存到“VideosLibrary”文件夹中的文件中,然后我立即播放录音:
/// <summary>
/// Stop recording and play it back
/// </summary>
private async void StopCapture()
{
Debug.WriteLine("Stopping recording");
await _mediaCaptureManager.StopRecordAsync();
Debug.WriteLine("Stop recording successful");
var stream = await _recordStorageFile.OpenAsync(FileAccessMode.Read);
Debug.WriteLine("Recording file opened");
playbackElement1.AutoPlay = true;
playbackElement1.SetSource(stream, _recordStorageFile.FileType);
playbackElement1.Play();
}
我应该注意,要播放录音,我必须在我的应用程序的 XAML 中添加一个,例如
<Canvas x:Name="playbackCanvas1">
<MediaElement x:Name="playbackElement1" />
</Canvas>
另一个从 Microsoft 的文档和代码示例中不明显的注意点是,您还需要在应用程序清单文件中启用“麦克风”和“视频库”权限。为此,请单击解决方案资源管理器中的 .appmanifest 文件,该文件位于项目的根级别。从那里,单击“功能”选项卡,然后您可以从那里启用麦克风和视频库。