0

我是 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 字节。有人知道为什么会发生吗?

4

1 回答 1

1

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

恐怕您无法在BackgroundTask. 来源于官方文档

InitializeAsync 应该从应用程序的主 UI 线程调用。应用程序必须通过正确清理媒体捕获资源来处理应用程序暂停或终止。有关正确关闭 MediaCapture 对象的信息

于 2020-08-20T12:27:15.023 回答