UWP:后台任务中的音频媒体捕获

UWP: Audio media capture in a background task

我是 UWP 的新手。我尝试通过 MediaCapture API.

从后台线程录制音频

我的代码在这里:

public sealed class Recorder : IBackgroundTask
    {
        private BackgroundTaskDeferral _deferral;
        private readonly MediaCapture mediaCapture = new MediaCapture();

        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();

            MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings()
            {
                StreamingCaptureMode = StreamingCaptureMode.Audio,
            };
            await mediaCapture.InitializeAsync(settings);

            var profile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);
            profile.Audio = AudioEncodingProperties.CreatePcm(16000, 1, 16);

            await StartRecordAsync(profile);

            _deferral.Complete();
        }

        private async Task StartRecordAsync(MediaEncodingProfile profile)
        {
            while(true)
            {
                StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                StorageFile storageFile = await storageFolder.CreateFileAsync(Guid.NewGuid() + ".wav", CreationCollisionOption.ReplaceExisting);

                await mediaCapture.StartRecordToStorageFileAsync(profile, storageFile);

                Task.Delay(10000).Wait();

                await mediaCapture.StopRecordAsync();
            }
        }
    }

它录制 .wav 文件每个 10 秒,但是当我播放这些文件时,我什么也听不到。每个文件都是 310KB+,所以它不是 0 字节。 有人知道为什么会这样吗?

It records .wav files 10 seconds each, but when I play these files, I hear nothing. Each file is 310KB+, so it isn't 0 bytes. Does somebody know why it would happen?

恐怕您无法在 BackgroundTask 中捕获音频。来源于官方document.

InitializeAsync should be called from the main UI thread of your app. Apps must handle app suspension or termination by properly cleaning up media capture resources. For information on shutting down the MediaCapture object properly