使用C#中的Json.Parse或Regex获取JSON响应的单行

问题描述 投票:2回答:1

我是初级Java开发人员,对C#不太好,所以我想在解决问题方面提供一些帮助。我想要做的是使用github上共享的现有代码,该代码接收麦克风输入,将其上传到Google Speech-to-Text API,然后返回带有成绩单的JSON响应。这部分工作正常。

什么不工作,是将JSON中返回的“Transcript:”的值存储到字符串变量中。

我尝试过多种方式,我已经找到了使用SimpleJSON和Newtonsoft将JSON响应转换为对象的方法,并且我还尝试使用正则表达式来读取以“transcript”开头的JSON行。我看到了我想要做的一个例子(下面链接),但是我遇到了编译器错误。如果有人可以帮助我,或者指出一个更好的结果,我会很感激。

这是我正在使用的代码。

//从https://github.com/steelejay/LowkeySpeech获得

using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Web;


[RequireComponent(typeof(AudioSource))]

public class GoogleVoiceSpeech : MonoBehaviour {

    public GUIText TextBox;

    struct ClipData {
        public int samples;
    }

    const int HEADER_SIZE = 44;

    private int minFreq;
    private int maxFreq;

    private bool micConnected = false;

    //A handle to the attached AudioSource
    private AudioSource goAudioSource;

    public string apiKey;

    // Use this for initialization
    void Start() {
        //Check if there is at least one microphone connected
        if (Microphone.devices.Length <= 0) {
            //Throw a warning message at the console if there isn't
            Debug.LogWarning("Microphone not connected!");
        } else //At least one microphone is present
          {
            //Set 'micConnected' to true
            micConnected = true;

            //Get the default microphone recording capabilities
            Microphone.GetDeviceCaps(null, out minFreq, out maxFreq);

            //According to the documentation, if minFreq and maxFreq are zero, the microphone supports any frequency...
            if (minFreq == 0 && maxFreq == 0) {
                //...meaning 44100 Hz can be used as the recording sampling rate
                maxFreq = 44100;
            }

            //Get the attached AudioSource component
            goAudioSource = this.GetComponent<AudioSource>();
        }
    }

    void OnGUI() {
        //If there is a microphone
        if (micConnected) {
            //If the audio from any microphone isn't being recorded
            if (!Microphone.IsRecording(null)) {
                //Case the 'Record' button gets pressed
                if (GUI.Button(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Record")) {
                    //Start recording and store the audio captured from the microphone at the AudioClip in the AudioSource
                    goAudioSource.clip = Microphone.Start(null, true, 7, maxFreq); //Currently set for a 7 second clip
                }
            } else //Recording is in progress
              {

                //Case the 'Stop and Play' button gets pressed
                if (GUI.Button(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Stop and Play!")) {
                    float filenameRand = UnityEngine.Random.Range(0.0f, 10.0f);

                    string filename = "testing" + filenameRand;

                    Microphone.End(null); //Stop the audio recording

                    Debug.Log("Recording Stopped");

                    if (!filename.ToLower().EndsWith(".wav")) {
                        filename += ".wav";
                    }

                    var filePath = Path.Combine("testing/", filename);
                    filePath = Path.Combine(Application.persistentDataPath, filePath);
                    Debug.Log("Created filepath string: " + filePath);

                    // Make sure directory exists if user is saving to sub dir.
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                    SavWav.Save(filePath, goAudioSource.clip); //Save a temporary Wav File
                    Debug.Log("Saving @ " + filePath);
                    //Insert your API KEY here.
                    string apiURL = "https://speech.googleapis.com/v1/speech:recognize?&key=AIzaSyAV65cThBBZAqmzW7MbWaccybtBrwY4Udc";
                    string Response;

                    Debug.Log("Uploading " + filePath);
                    Response = HttpUploadFile(apiURL, filePath, "file", "audio/wav; rate=44100");
                    Debug.Log("Response String: " + Response);

                    var jsonresponse = SimpleJSON.JSON.Parse(Response);

                    if (jsonresponse != null) {
                        string resultString = jsonresponse["result"][0].ToString();
                        var jsonResults = SimpleJSON.JSON.Parse(resultString);

                        string transcripts = jsonResults["alternative"][0]["transcript"].ToString();

                        Debug.Log("transcript string: " + transcripts);
                        TextBox.text = transcripts;

                    }
                    //goAudioSource.Play(); //Playback the recorded audio

                    File.Delete(filePath); //Delete the Temporary Wav file

                }

                GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height / 2 + 25, 200, 50), "Recording in progress...");
            }
        } else // No microphone
          {
            //Print a red "Microphone not connected!" message at the center of the screen
            GUI.contentColor = Color.red;
            GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Microphone not connected!");
        }
    }

    public string HttpUploadFile(string url, string file, string paramName, string contentType) {

        System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
        Debug.Log(string.Format("Uploading {0} to {1}", file, url));

        Byte[] bytes = File.ReadAllBytes(file);
        String file64 = Convert.ToBase64String(bytes,
                                         Base64FormattingOptions.None);

        Debug.Log(file64);

        try {

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {




                string json = "{ \"config\": { \"languageCode\" : \"en-US\" }, \"audio\" : { \"content\" : \"" + file64 + "\"}}";

                Debug.Log(json);
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            Debug.Log(httpResponse);

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
                var result = streamReader.ReadToEnd();
                Debug.Log("Response:" + result);

            }

        }
        catch (WebException ex) {
            var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
            Debug.Log(resp);

        }


        return "empty";

    }

}

我正在使用JSON结果返回正确的控制台消息。我只需要将“transcript”值转换为String。以下是Google API的响应示例。

Response:{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "this is a test",
          "confidence": 0.98762906
        }
      ]
    }
  ]
}

SimpleJSON框架的实际创建者在几年前回复了类似问题的人,但是当我尝试实现类似的修复时,我得到错误,因为我的回答是单数的。

https://answers.unity.com/questions/1443367/get-json-array-object-string-value.html

我很感激任何人的帮助或指导。我一直在网上找了几天试图让这个工作起来,并且在发布之前问过同事(因为他们缺乏C#而无法帮助我)。

c# json regex string speech-to-text
1个回答
4
投票

Newtonsoft是一个更好的选择,我将引导您完成如何使用它。

首先,create the C# classes你需要保存解析的结果。在您的示例中,它们将如下所示:

public class SpeechResponse
{
    public Result[] results { get; set; }
}

public class Result
{
    public Alternative[] alternatives { get; set; }
}

public class Alternative
{
    public string transcript { get; set; }
    public float confidence { get; set; }
}

您已经知道如何获取JSON数据,因此我们假设它已保存在String json中。您可以使用以下命令将字符串转换为C#类:

var response = JsonConvert.DeserializeObject<SpeechResponse>( json );

您正在寻找的具体数据可以像这样获得:

string phrase = response.results[0].alternatives[0].transcript;

奖金提示 如果您使用的是Visual Studio,则可以通过复制JSON示例数据并选择“编辑 - >选择性粘贴 - >将JSON粘贴为类”(Read More)来轻松创建类定义。

© www.soinside.com 2019 - 2024. All rights reserved.