UnauthorizedAccessException 或如何为 UWP 应用程序启用麦克风

UnauthorizedAccessException or how to Enable Microfone for UWP Application

对于我的第一个 UWP 应用程序项目,我想构建一个带有语音识别功能的小型测试程序。

通过一些教程搜索后,我想出了以下代码:

private async void initSpeechParts() {
    try {
        if (_recognizer == null) {
            _recognizer = new SpeechRecognizer();
            var lang= _recognizer.CurrentLanguage;
            var functionGrammar = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.Dictation, "Functioncall");
            _recognizer.UIOptions.AudiblePrompt = "Give me the name of a Function";
            _recognizer.UIOptions.ExampleText = "Function A";
            _recognizer.Constraints.Add(functionGrammar) ;
            await _recognizer.CompileConstraintsAsync();
        }

        try {
            // Start recognition.
            SpeechRecognitionResult speechRecognitionResult = await _recognizer.RecognizeWithUIAsync();
            var recognizedText = speechRecognitionResult.Text;
            recognizedText = removetokens(recognizedText);
            callTestfunction(recognizedText);
        } catch (Exception ex2) {
            var ee = ex2.Message;
            throw;
        }                    
    } catch (Exception ex) {
        //Check if user has approved the privacy policy
        const uint HresultPrivacyStatementDeclined = 0x80045509;
        if ((uint)ex.HResult == HresultPrivacyStatementDeclined)
        {
            var messageDialog = new Windows.UI.Popups.MessageDialog(
                "You must accept the speech privacy policy to continue", "Speech Exception");
            messageDialog.ShowAsync().GetResults();
        }
    }
}

我目前关于此代码的问题是,在它说的那一行:

SpeechRecognitionResult speechRecognitionResult = await _recognizer.RecognizeWithUIAsync();

我总是收到 UnauthorizedAccess 异常。在阅读 Google 上的一些帖子后,我开始认为这可能是因为该应用程序与我的麦克风有一些问题。那么如何为我的应用程序启用麦克风?

您可能想念 package.appxmanifest 中的麦克风功能 只需在 Visual Studio 中打开清单并从功能选项卡中添加 microphone 功能。

如果需要,您还可以在这里找到演讲样本:https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/SpeechRecognitionAndSynthesis/cpp/Package.appxmanifest