0

In my Rails 5.1.7 application, I want to use a method within a rake-task to turn text into a mp3 audiofile. I'm using the google-cloud-text_to_speech gem for doing so. Here's part of my setup:

/Gemfile:

gem 'google-cloud-text_to_speech'

Here is the method in the task-file that is being called from within the task:

/lib/tasks/sync.rake:

require "google/cloud/text_to_speech"

def create_speech(content, id)
  text_to_speech_client = Google::Cloud::TextToSpeech.new
  text = content
  input = { text: text }
  language_code = "nl-NL"
  voice = { language_code: language_code }
  audio_encoding = :MP3
  audio_config = { audio_encoding: audio_encoding }
  response = text_to_speech_client.synthesize_speech(input, voice, audio_config)
  File.write("speach_id_#{id}.mp3", response.audio_content, mode: "wb")
  puts "Created speach_id_#{id}.mp3"
end

I authenticated it according to the following instructions: https://googleapis.dev/ruby/google-cloud-text_to_speech/latest/file.AUTHENTICATION.html

/config/application.rb:

config.speech = config_for(:speech)

/config/speech.yml:

google:
  project: ENV=["TEXTTOSPEECH_PROJECT"]
  credentials: ENV=["TEXTTOSPEECH_CREDENTIALS"]

I'm using Figaro for my environment variables and therefore I have an application.yml file.

/config/application.yml:

development:
  TEXTTOSPEECH_PROJECT: "project-id"
  TEXTTOSPEECH_CREDENTIALS: "/path/to/file.json"

And then I run my task:

$ bundle exec rake sync:feeds

When I run the rake task without the extra method, everything works fine. But when I use the method, I'm getting:

"rake aborted!
Could not load the default credentials. Browse to
https://developers.google.com/accounts/docs/application-default-credentials"

I've tried many different ways to offer the credentials, but I'm getting the same error time after time. Is there anyone who can help me out?

  • I would suggest putting your credentials inside your `Rails Credentials` file and then referencing the credentials with something like this `Rails.application.credentials.google[:api_key]`. – Cannon Moyer Dec 27 '19 at 16:02
  • Thank you for your reaction, Cannon. Isn’t the credentials file something that we use in Rails 6? For this project I’m still in 5.1.7. And where should I reference it? Do I need to replace api_key with another value? – Sebastian Plasschaert Dec 28 '19 at 06:40
  • If I remember correctly credentials were introduced in Rails 5.2 while Rails secrets weren't fully removed until Rails 6. So, if you're on 5.1 I would suggest using secrets. The functionality is very similar to Rails credentials. This should solve your problem with the file not loading. Here is a link to more information about Rails secrets. https://guides.rubyonrails.org/4_1_release_notes.html#config-secrets-yml – Cannon Moyer Dec 29 '19 at 21:39

0 Answers0