Google Cloud语音到文本访问令牌问题

时间:2020-10-29 23:05:00

标签: google-oauth access-token speech-to-text

我正在使用Google Cloud语音到文本API,目前具有以下代码。问题是,当通过Speech-to-tex REST API发布数据时,API返回错误:

{ “错误”:{ “代码”:401, “ message”:“请求具有无效的身份验证凭据。预期的OAuth 2访问令牌,登录cookie或其他有效的身份验证凭据。请参见https://developers.google.com/identity/sign-in/web/devconsole-project.", “状态”:“未经授权” } }

现在在下面的代码中,我专门通过gapi请求accessToken。无法弄清楚我在做什么错以及为什么我得到了无效的访问令牌。这是代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Google Cloud Speech 2 Text Rest API</title>
    <meta charset='utf-8' />
  </head>
  <body>
    <p>Google Cloud Speech 2 Text Rest API</p>

    <!--Add buttons to initiate auth sequence and sign out-->
    <button id="authorize-button" style="display: none;">Authorize</button>
    <button id="signout-button" style="display: none;">Sign Out</button>

    <div id="content">
    <video autoplay></video>
    <div id="screen_div"></div>  
    </div>

    <script type="text/javascript">
      // Enter an API key from the Google API Console:
      //   https://console.developers.google.com/apis/credentials
      var apiKey = '< google cloud api key>';

      // Enter the API Discovery Docs that describes the APIs you want to
      // access. In this example, we are accessing the People API, so we load
      // Discovery Doc found here: https://developers.google.com/people/api/rest/
      var discoveryDocs = ["https://speech.googleapis.com/$discovery/rest?version=v1"];
      //var discoveryDocs = ["https://speech.googleapis.com/$discovery/rest?version=v1p1beta1"]; //For v1p1beta1 api

      // Enter a client ID for a web application from the Google API Console:
      //   https://console.developers.google.com/apis/credentials?project=_
      // In your API Console project, add a JavaScript origin that corresponds
      //   to the domain where you will be running the script.
      var clientId = '<google cloud client id>';

      // Enter one or more authorization scopes. Refer to the documentation for
      // the API or https://developers.google.com/people/v1/how-tos/authorizing
      // for details.
      var scopes = 'https://www.googleapis.com/auth/cloud-platform';

      var authorizeButton = document.getElementById('authorize-button');
      var signoutButton = document.getElementById('signout-button');
      
      var accessToken = null;
        
      function handleClientLoad() {
        // Load the API client and auth2 library
        gapi.load('client:auth2', initClient);
      }

      function initClient() {
        gapi.client.init({
            apiKey: apiKey,
            discoveryDocs: discoveryDocs,
            clientId: clientId,
            scope: scopes
        }).then(function () {
          // Listen for sign-in state changes.
          accessToken = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse(1).access_token;
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());

          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
        });
      }

      function updateSigninStatus(isSignedIn) {
        if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';
          makeApiCall();
        } else {
          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
        }
      }

      function handleAuthClick(event) {
        gapi.auth2.getAuthInstance().signIn();
      }

      function handleSignoutClick(event) {
        gapi.auth2.getAuthInstance().signOut();
      }
        
      var stt_config = {
          "encoding": "OGG_OPUS",
          "sampleRateHertz": 48000,
          "audioChannelCount": 1,
          "enableSeparateRecognitionPerChannel": false,
          "languageCode": "en-US",
          "maxAlternatives": 10,
          "profanityFilter": true,
          "enableWordTimeOffsets": false,
          "enableAutomaticPunctuation": true,
          "model": "default",
          "useEnhanced": false
        }
        
      // Load the API and make an API call.  Display the results on the screen.
      function makeApiCall() {
          getStream();
      }
      </script>
      <script src="https://apis.google.com/js/api.js" 
        onload="this.onload=function(){};handleClientLoad()" 
        onreadystatechange="if (this.readyState === 'complete') this.onload()">
      </script>

      <script>
      const constraints = {
        video: false,
        audio: true
      };

      const video = document.querySelector('video');

      function getUserMedia(options, successCallback, failureCallback) {
        var api = navigator.getUserMedia || navigator.webkitGetUserMedia ||
          navigator.mozGetUserMedia || navigator.msGetUserMedia;
        if (api) {
          return api.bind(navigator)(options, successCallback, failureCallback);
        }
      }

      var theStream;
      var theRecorder;
      var recordedChunks = [];

      function getStream() {
        if (!navigator.getUserMedia && !navigator.webkitGetUserMedia &&
          !navigator.mozGetUserMedia && !navigator.msGetUserMedia) {
          alert('User Media API not supported.');
          return;
        }

        var constraints = {video: true, audio: true};
        getUserMedia(constraints, function (stream) {
          var mediaControl = document.querySelector('video');

          if ('srcObject' in mediaControl) {
            mediaControl.srcObject = stream;
          } else if (navigator.mozGetUserMedia) {
            mediaControl.mozSrcObject = stream;
          } else {
            mediaControl.src = (window.URL || window.webkitURL).createObjectURL(stream);
          }

          theStream = stream;
          try {
            recorder = new MediaRecorder(stream, {mimeType : "audio/webm"});
          } catch (e) {
            console.error('Exception while creating MediaRecorder: ' + e);
            return;
          }
          theRecorder = recorder;
          console.log('MediaRecorder created');
          recorder.ondataavailable = recorderOnDataAvailable;
          recorder.start(100);
        }, function (err) {
          alert('Error: ' + err);
        });
      }

      function recorderOnDataAvailable(event) {
        if (event.data.size == 0) return;
        recordedChunks.push(event.data);
      }
        
        
     const audioBlob = new Blob(recordedChunks, { 'type': 'audio/webm' });
            const audioUrl = URL.createObjectURL(audioBlob);
            const audio = new Audio(audioUrl);
            //audio.play();

            var encodedAudio = btoa(audioUrl); // encode to base 64
            console.log(audioBlob);
            console.log(audioUrl);
            console.log(encodedAudio);

            document.getElementById("screen_div").innerHTML += "<audio controls src=\"" + audioUrl + "\"></audio>";

            var params = {
              "config": {
              "encoding": "OGG_OPUS",
              "sampleRateHertz": 48000,
              "audioChannelCount": 1,
              "enableSeparateRecognitionPerChannel": false,
              "languageCode": "en-US",
              "maxAlternatives": 10,
              "profanityFilter": true,
              "enableWordTimeOffsets": false,
              "enableAutomaticPunctuation": true,
              "model": "default",
              "useEnhanced": false
              },
              "audio": {
                "content": encodedAudio
              }
            };

            var xhrSpeechToText = new XMLHttpRequest();
            xhrSpeechToText.open('POST', 'https://speech.googleapis.com/v1/speech:recognize');
            xhrSpeechToText.setRequestHeader('Authorization', 'Bearer ' + accessToken);     
            xhrSpeechToText.setRequestHeader("Content-Type", "application/json");       

            xhrSpeechToText.send(JSON.stringify(params));
            xhrSpeechToText.onload = function() {
                var xhrTextResponse = JSON.parse(xhrSpeechToText.response);
                console.log(xhrTextResponse);
            }
    </script>  
      
      
  </body>
</html>

任何想法或建议将不胜感激。

0 个答案:

没有答案