Skip to content

Instantly share code, notes, and snippets.

@florabtw
Last active February 9, 2021 18:21
Show Gist options
  • Save florabtw/03a9ffa7373c726335e9b8af20c0835d to your computer and use it in GitHub Desktop.
Save florabtw/03a9ffa7373c726335e9b8af20c0835d to your computer and use it in GitHub Desktop.
Example Usage of Sound of Text API
/* Downloads 'Hello, World', spoken in English, to ./hello.mp3 */
const http = require('https');
const fs = require('fs');
/* Set up handler for response from initial POST request */
function handlePostResponse(data) {
const response = JSON.parse(data); // parse response body from POST
const isSuccess = response.success;
if (!isSuccess) {
console.log(response.message);
process.exit(1); // something went wrong; exit
}
const soundId = response.id;
requestStatus(soundId);
}
/* Set up a function to check for status and handle different statuses */
function requestStatus(soundId) {
http.get(`https://api.soundoftext.com/sounds/${soundId}`, response => {
let data = '';
response.on('data', chunk => (data += chunk));
response.on('end', () => handleStatusResponse(data, soundId));
response.on('error', console.log);
});
}
function handleStatusResponse(data, soundId) {
const response = JSON.parse(data);
const status = response.status;
if (status === 'Pending') {
// wait before requesting again
setTimeout(() => requestStatus(soundId), 2000);
} else if (status === 'Error') {
console.log(response.message);
process.exit(1); // something went wrong; exit
} else {
// must be 'Success', so download the file
downloadFilePath(response);
}
}
/* Download the file */
function downloadFilePath(data) {
const path = data.location;
const file = fs.createWriteStream('./hello.mp3');
http.get(path, response => {
response.pipe(file);
file.on('finish', () => file.close());
});
}
/* Kick off initial POST to https://api.soundoftext.com/sounds */
const postOptions = {
hostname: 'api.soundoftext.com',
path: '/sounds',
port: 443,
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
};
const postData = JSON.stringify({
engine: 'Google',
data: {
text: 'Hello, world',
voice: 'en-US',
},
});
const req = http.request(postOptions, response => {
let data = '';
response.on('data', chunk => (data += chunk));
response.on('end', () => handlePostResponse(data));
response.on('error', console.log);
});
req.write(postData);
req.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment