Create an Audio Message from text in Google Docs

1. Get Secrets to access your docs

  1. Create a project and enable the API in Google Developers. Follow the instructions at: In the 5th step at Enable a Google Workspace API, select "Google Docs API".
  2. Create your credentials with OAuth. Follow the instructions given at for a Desktop application:
  1. Go to your Google Cloud > API and Services > Credentials. Under Client ID OAuth 2.0 there is a new row with your client ID information. At the right of the row there is an arrow. Click it and download the secrets and rename the json file as "credentials.json"

2. Google Quickstarts

Click the following link to set up the connection with the API. Write the "" documents and run it. Make sure that "credentials.json" is in the same folder as "".
At the end of the step 3, if you can see "The title of the document is: Docs API Quickstart" the set up is ready!
javascript (node.js):

3. Get a Speech from your Document

It is easy to add this functionality to the quickstart document. Just copy the code below and chose the document you would like to listen. To find the document id, open the document and copy the secret at the URL.
As an example, in the following URL "", the client id is "1xENxi5emRbFGiG1QS3Bt3Yu_vSYYQ3m7M-4xe5hqHwo".

Feel free to personalize your audio clip modifing the voice, speed, audio padding and more!

from __future__ import print_function
import os.path
import apiaudio
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# If modifying these scopes, delete the file token.json.
SCOPES = ['']

# The ID of a sample document.

def apiaudio_create(scriptName, message):
    apiaudio.api_key = APIAUDIO_API_KEY
    script = apiaudio.Script().create(scriptText= message, scriptName=scriptName)
    response = apiaudio.Speech().create(scriptId=script.get("scriptId"), voice="Emma", speed=str(120), silence_padding = str(1000 * 3))
    audio_files = apiaudio.Speech().download(scriptId=script.get("scriptId"), destination=".") #Download the speech
    response = apiaudio.Mastering().create(scriptId=script.get("scriptId"),soundTemplate="heatwave")
    apiaudio.Mastering().download(scriptId=script.get("scriptId"), destination=".") #Download the full audio file (speech with background music)

def main():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:

    service = build('docs', 'v1', credentials=creds)

    document = service.documents().get(documentId=DOCUMENT_ID).execute()
    fullText = ""
    for paragraph in document["body"]["content"]:
        if paragraph != document["body"]["content"][0]:
            text = paragraph["paragraph"]["elements"][0]["textRun"]["content"]
            # print(text)
            fullText += text
    apiaudio_create("googleDocs", fullText)

if __name__ == '__main__':
const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");
const Aflr = require("aflr").default;

const YOUR_AFLR_API_KEY = "-";
let fullText;

const SCOPES = [""];

const TOKEN_PATH = "token.json";

// Load client secrets from a local file.
fs.readFile("credentials.json", async (err, content) => {
  if (err) return console.log("Error loading client secret file:", err);
  // Authorize a client with credentials, then call the Google Docs API.
  fullText = authorize(JSON.parse(content), printDocContent);

 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
function authorize(credentials, callback) {
  const { client_secret, client_id, redirect_uris } = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);

 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: "offline",
    scope: SCOPES,
  console.log("Authorize this app by visiting this url:", authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  rl.question("Enter the code from that page here: ", (code) => {
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error("Error retrieving access token", err);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) console.error(err);
        console.log("Token stored to", TOKEN_PATH);

 * Prints the title of a sample doc:
 * @param {google.auth.OAuth2} auth The authenticated Google OAuth 2.0 client.
function printDocContent(auth) {
  const docs ={ version: "v1", auth });
      documentId: "-",
    (err, res) => {
      if (err) return console.log("The API returned an error: " + err);
      var stepText = "";
      for (i = 1; i <; i++) {
        var text =
        // console.log(text);
        stepText = stepText.concat(text);

async function aflr(text) {
  try {
    Aflr.configure({ apiKey: YOUR_AFLR_API_KEY });
    const script = await Aflr.Script.create({
      scriptText: text,
    const response = await Aflr.Speech.create({
      scriptId: script["scriptId"],
      voice: "Emma",
      speed: "90",
    const audio_files = await Aflr.Speech.retrieve(script["scriptId"]); // retrieve url
      scriptId: script["scriptId"],
      backgroundTrackId: "full__citynights.wav", // define mastering background track
    const url = await Aflr.Mastering.retrieve(script["scriptId"]); // download mastered speech
  } catch (e) {

Did this page help you?