首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >同时录制音频和播放声音- C# - Windows 8.1

同时录制音频和播放声音- C# - Windows 8.1
EN

Stack Overflow用户
提问于 2015-09-06 20:31:05
回答 1查看 2.6K关注 0票数 3

我正在尝试录制音频并直接播放它(我想在耳机中听到我的声音而不保存它),但是MediaElement和MediaCapture似乎不能同时工作。我初始化了我的MediaCapture,以便:

代码语言:javascript
运行
复制
    _mediaCaptureManager = new MediaCapture();
    var settings = new MediaCaptureInitializationSettings();
    settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
    settings.MediaCategory = MediaCategory.Other;
    settings.AudioProcessing = AudioProcessing.Default;
    await _mediaCaptureManager.InitializeAsync(settings);

然而,我真的不知道该如何进行;我想知道这些方法中的一种是否可行(我尝试实现它们但没有成功,我也没有找到例子):

  1. 是否有一种使用StartPreviewAsync()录制音频的方法,或者它只适用于视频?我注意到,在设置CaptureElement源代码时,我得到了以下错误:“指定的对象或值不存在”;只有在编写"settings.StreamingCaptureMode = StreamingCaptureMode.Audio;“时,所有的对象或值都为.Video工作时才会发生。
  2. 如何使用StartRecordToStreamAsync()记录流;我的意思是,如何初始化IRandomAccessStream并从中读取?我能在小溪上写字吗?
  3. 我读到,将AudioCathegory of MediaElement和MediaCathegory of MediaCapture改为Communication是有可能的。但是,虽然我的代码可以用前面的设置记录和保存(只需在文件中记录和保存),但是如果我编写了"settings.MediaCategory = MediaCategory.Communication;“而不是"settings.MediaCategory = MediaCategory.Other;”,它就不能工作。你能告诉我为什么吗?下面是我当前的程序,它只记录、保存和播放:私有异步空MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);CaptureAudio() { _recordStorageFile =等待_mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile,CreationCollisionOption.GenerateUniqueName);MediaEncodingProfile recordProfile =MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile,this._recordStorageFile);_recording = true;} catch (异常e) {Debug.WriteLine(“未能捕获音频:”+e.Message);}私有异步StopCapture() { if ( _recording ) {等待_mediaCaptureManager.StopRecordAsync();_recording= false;}私有异步虚PlayRecordedCapture() { if (!_recording) { var流=等待StopCaptureplaybackElement1.AutoPlay = true;playbackElement1.SetSource(流,_recordStorageFile.FileType);playbackElement1.Play();}}

如果你有什么建议,我会很感激的。祝你今天愉快。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-09 17:56:55

你会考虑以Windows 10为目标吗?新的AudioGraph API允许您这样做,SDK示例中的场景2(设备捕获)很好地演示了它。

首先,示例将所有输出设备填充到列表中:

代码语言:javascript
运行
复制
private async Task PopulateDeviceList()
{
    outputDevicesListBox.Items.Clear();
    outputDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioRenderSelector());
    outputDevicesListBox.Items.Add("-- Pick output device --");
    foreach (var device in outputDevices)
    {
        outputDevicesListBox.Items.Add(device.Name);
    }
}

然后构建AudioGraph:

代码语言:javascript
运行
复制
AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media);
settings.QuantumSizeSelectionMode = QuantumSizeSelectionMode.LowestLatency;

// Use the selected device from the outputDevicesListBox to preview the recording
settings.PrimaryRenderDevice = outputDevices[outputDevicesListBox.SelectedIndex - 1];

CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings);

if (result.Status != AudioGraphCreationStatus.Success)
{
    // TODO: Cannot create graph, propagate error message
    return;
}

AudioGraph graph = result.Graph;

// Create a device output node
CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await graph.CreateDeviceOutputNodeAsync();
if (deviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
{
    // TODO: Cannot create device output node, propagate error message
    return;
}

deviceOutputNode = deviceOutputNodeResult.DeviceOutputNode;

// Create a device input node using the default audio input device
CreateAudioDeviceInputNodeResult deviceInputNodeResult = await graph.CreateDeviceInputNodeAsync(MediaCategory.Other);

if (deviceInputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
{
    // TODO: Cannot create device input node, propagate error message
    return;
}

deviceInputNode = deviceInputNodeResult.DeviceInputNode;

// Because we are using lowest latency setting, we need to handle device disconnection errors
graph.UnrecoverableErrorOccurred += Graph_UnrecoverableErrorOccurred;

// Start setting up the output file
FileSavePicker saveFilePicker = new FileSavePicker();
saveFilePicker.FileTypeChoices.Add("Pulse Code Modulation", new List<string>() { ".wav" });
saveFilePicker.FileTypeChoices.Add("Windows Media Audio", new List<string>() { ".wma" });
saveFilePicker.FileTypeChoices.Add("MPEG Audio Layer-3", new List<string>() { ".mp3" });
saveFilePicker.SuggestedFileName = "New Audio Track";
StorageFile file = await saveFilePicker.PickSaveFileAsync();

// File can be null if cancel is hit in the file picker
if (file == null)
{
    return;
}

MediaEncodingProfile fileProfile = CreateMediaEncodingProfile(file);

// Operate node at the graph format, but save file at the specified format
CreateAudioFileOutputNodeResult fileOutputNodeResult = await graph.CreateFileOutputNodeAsync(file, fileProfile);

if (fileOutputNodeResult.Status != AudioFileNodeCreationStatus.Success)
{
    // TODO: FileOutputNode creation failed, propagate error message
    return;
}

fileOutputNode = fileOutputNodeResult.FileOutputNode;

// Connect the input node to both output nodes
deviceInputNode.AddOutgoingConnection(fileOutputNode);
deviceInputNode.AddOutgoingConnection(deviceOutputNode);

完成所有这些之后,您可以在播放录制的音频的同时将其记录到文件中,如下所示:

代码语言:javascript
运行
复制
private async Task ToggleRecordStop()
{
    if (recordStopButton.Content.Equals("Record"))
    {
        graph.Start();
        recordStopButton.Content = "Stop";
    }
    else if (recordStopButton.Content.Equals("Stop"))
    {
        // Good idea to stop the graph to avoid data loss
        graph.Stop();
        TranscodeFailureReason finalizeResult = await fileOutputNode.FinalizeAsync();
        if (finalizeResult != TranscodeFailureReason.None)
        {
            // TODO: Finalization of file failed. Check result code to see why, propagate error message
            return;
        }

        recordStopButton.Content = "Record";
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32428000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档