You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails中Google Cloud Text-to-Speech API认证配置疑问

Google Cloud Text-to-Speech Ruby on Rails 认证配置方案

一、认证配置两种场景方案

1. 本地开发环境

直接在初始化客户端时指定服务账号密钥文件路径,和你用Active Storage时的配置逻辑一致:

client = Google::Cloud::TextToSpeech::Client.new(
  credentials: Rails.root.join("google-credentials.json")
)

也可以通过环境变量让客户端自动读取密钥:在本地.env文件中添加(.env需加入.gitignore):

GOOGLE_APPLICATION_CREDENTIALS=./google-credentials.json

此时初始化客户端无需手动传credentials参数,库会自动读取环境变量指向的文件。

2. Heroku生产环境

Heroku无法直接存储密钥文件,需将密钥内容转为环境变量:

  1. 在本地终端执行命令,把密钥文件内容存入Heroku环境变量:
heroku config:set GOOGLE_CLOUD_CREDENTIALS="$(cat google-credentials.json)"
  1. 代码中读取环境变量初始化客户端:
client = Google::Cloud::TextToSpeech::Client.new(
  credentials: JSON.parse(ENV["GOOGLE_CLOUD_CREDENTIALS"])
)

二、修正后的synthesize_speech方法

你原代码存在客户端初始化方式错误、参数格式不匹配、响应解析冗余等问题,修正后代码如下:

def synthesize_speech
  # 根据环境自动切换认证方式
  client = Rails.env.production? ? 
    Google::Cloud::TextToSpeech::Client.new(credentials: JSON.parse(ENV["GOOGLE_CLOUD_CREDENTIALS"])) :
    Google::Cloud::TextToSpeech::Client.new(credentials: Rails.root.join("google-credentials.json"))

  # 发起语音合成请求
  response = client.synthesize_speech(
    input: { text: self.content },
    voice: {
      language_code: "en-US",
      name: "en-US-Studio-M",
      ssml_gender: "MALE"
    },
    audio_config: { audio_encoding: "MP3" }
  )

  audio_base64 = response.audio_content

  # 选项1:将base64内容存入数据库
  self.base64 = audio_base64

  # 选项2:写入临时文件
  File.open("/tmp/audio_base64.txt", "w") do |f|
    f.write(audio_base64)
  end

  save # 记得保存模型变更
end

注意:Ruby客户端库使用蛇形命名参数(如language_code),会自动转换为API要求的驼峰格式,无需手动转JSON;响应对象直接通过audio_content属性获取base64内容,无需解析JSON。

内容的提问来源于stack exchange,提问作者Patrick Vellia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:22:40