使用Google语音时从Google Cloud Storage访问音频文件

问题描述:

我已经使用下面这段代码,使用Google语音成功解析了包含语音和文本的.wav文件。使用Google语音时从Google Cloud Storage访问音频文件

但是我想访问一个不同的.wav文件,我已经在Google Cloud Storage(公开)上放置了一个不同的.wav文件,而不是在本地硬盘上。为什么不能简单地改变

speech_file = 'my/local/system/sample.wav'


speech_file = 'https://console.cloud.google.com/storage/browser/speech_proj_files/sample.wav'

工作可以接受?

这里是我的代码:

speech_file = 'https://console.cloud.google.com/storage/browser/speech_proj_files/sample.wav' 

DISCOVERY_URL = ('https://{api}.googleapis.com/$discovery/rest?' 
       'version={apiVersion}') 


def get_speech_service(): 
    credentials = GoogleCredentials.get_application_default().create_scoped(
     ['https://www.googleapis.com/auth/cloud-platform']) 
    http = htt|plib2.Http() 
    credentials.authorize(http) 

    return discovery.build(
     'speech', 'v1beta1', http=http, discoveryServiceUrl=DISCOVERY_URL) 

def main(speech_file): 
    """Transcribe the given audio file. 

    Args: 
     speech_file: the name of the audio file. 
    """ 
    with open(speech_file, 'rb') as speech: 
     speech_content = base64.b64encode(speech.read()) 

    service = get_speech_service() 
    service_request = service.speech().syncrecognize(
     body={ 
      'config': { 
       'encoding': 'LINEAR16', # raw 16-bit signed LE samples 
       'sampleRate': 44100, # 16 khz 
       'languageCode': 'en-US', # a BCP-47 language tag 
      }, 
      'audio': { 
       'content': speech_content.decode('UTF-8') 
       } 
      }) 
    response = service_request.execute() 
    return response 

我不知道为什么你的做法是行不通的,但我想提供一个快速的建议。

Google Cloud Speech API本身支持Google Cloud Storage对象。而不是下载整个对象只把它上传回云语音的API,只需指定通过交换该线路的对象:

 'audio': { 
      # Remove this: 'content': speech_content.decode('UTF-8') 
      'uri': 'gs://speech_proj_files/sample.wav' # Do this! 
      } 

另外一个建议。您可能会发现Python库更易于使用。试试这个:

from google.cloud import speech 
speech_client = speech.Client() 

audio_sample = speech_client.sample(
    content=None, 
    source_uri='gs://speech_proj_files/sample.wav', 
    encoding='LINEAR16', 
    sample_rate_hertz= 44100) 
results_list = audio_sample.sync_recognize(language_code='en-US') 

这里有一些很好的例子:https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/speech/cloud-client

+0

的第二个代码块似乎运作良好,我只是在时遇到访问存储在'results_list'什么。这是一个对象,而不是一个列表,这是肯定的......看起来不像JSON ......它是什么以及如何闯入它? 'results_list.response'即将变空。也许它并没有真正的工作。 –

+0

我整天搞砸了 - 我最终问了另一个问题http://stackoverflow.com/questions/43555694/audio-file-isnt-being-parsed-with-google-speech再次感谢您对此的帮助。那意义重大。 –

+0

@BrandonYarbrough我认为莫妮卡想知道的是如何在没有公开对象的情况下访问她的对象。 –