首页 > 解决方案 > Rails + 谷歌 TTS。Google::Cloud::ResourceExhaustedError 8:收到的消息大于最大值(5250205 与 4194304)

问题描述

我的课:

class TtsGoogle

def initialize
  @google_client = Google::Cloud::TextToSpeech.text_to_speech    
end

def write_file(topic)
  text = topic.content
  spaces = text.enum_for(:scan, /(?=\s)/).map { Regexp.last_match.offset(0).first }
  start = finish = limit = 0
  result = ''

  while true do
    #Google TTS limit 5000
    limit += 4800
    if limit < text.length
      finish = spaces.select {|n| n > limit }.first
      result += get_audio_content(text[start..finish])
      start = finish
    else
      result += get_audio_content(text[start..text.length])
      break
    end
  end

  File.open "#{topic.name.gsub('/', ' ')}.wav", "wb" do |file|
    file.write result
  end
end

def delete_file(name)
  File.delete("#{name.gsub('/', ' ')}.wav")
end

private

def get_audio_content(text)
  synthesis_input = { text: text }

  response = @google_client.synthesize_speech(
    input:        synthesis_input,
    voice:        voice_config,
    audio_config: audio_config
  )

  response.audio_content
end

def voice_config
  @voice_config ||= {
    language_code: "en-US",
    ssml_gender:   "NEUTRAL",
    name: "en-US-Wavenet-B"
  }
end

def audio_config
  @audio_config = { audio_encoding: "LINEAR16", speaking_rate: 0.90 }
end

end

当我尝试从大文本创建音频时,我遇到了这个问题:

Google::Cloud::ResourceExhaustedError 8:Received message larger than max (5250205 vs. 4194304)

当输出的音频小于 4MB 时,它可以使用小文本。如何增加或禁用此 4MB 限制?我找到了一些 PHP 的解决方案,下一个使用方式:

-$client = new TextToSpeechClient();
+$client = new TextToSpeechClient([
             'transportConfig' => [
                 'grpc' => [
                     'stubOpts' => [
                         'grpc.max_receive_message_length' => -1,
                         'grpc.max_send_message_length' => -1
                     ]
                 ]
             ]
         ]);

但我不知道如何用 Rails 解决这个问题。请帮忙。

标签: ruby-on-railsrubyrubygemstext-to-speech

解决方案


推荐阅读