2017-04-21 121 views
2

我已經使用下面這段代碼,使用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 

回答

3

我不知道爲什麼你的做法是行不通的,但我想提供一個快速的建議。

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我認爲莫妮卡想知道的是如何在沒有公開對象的情況下訪問她的對象。 –

相關問題