Метод загрузки GCS
Я работаю сGoogle Text To Speech (TTS) чтобы сохранить сгенерированный двоичный аудиофайл вGoogle Cloud Storage (GCS).
Сохранение локального двоичного файла не кажется хорошей идеей в среде облачных функций Firebase. Поэтому я ищуКак написать и получить временный двоичный файл? Когда я пытаюсь получить временный файл, созданный в настоящее время, я получаю сообщение об ошибке.
В приведенном ниже попытке решения временный файл отображается как сохраненный в журнале, затем я пытаюсь получить временный файл в успешной части обратного вызова для создания файла.
ошибкаError: Cannot parse JSON response
at ApiError (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/build/src/util.js:43:9)
at Util.parseHttpRespBody (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/build/src/util.js:167:42)
at Util.handleResp (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/build/src/util.js:116:117)
at retryRequest (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/build/src/util.js:403:22)
at onResponse (/user_code/node_modules/@google-cloud/storage/node_modules/retry-request/index.js:200:7)
at /user_code/node_modules/@google-cloud/storage/node_modules/teeny-request/build/src/index.js:158:17
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Попытка решенияconst admin = require('firebase-admin');
const functions = require('firebase-functions');
const path = require('path');
const os = require('os');
const {Storage} = require('@google-cloud/storage');
const projectId = 'coinverse-media-staging';
const storage = new Storage({
projectId: projectId,
});
const fs = require('fs');
const textToSpeech = require('@google-cloud/text-to-speech');
const client = new textToSpeech.TextToSpeechClient();
admin.initializeApp();
const text = 'Hello, world!';
const request = {
input: {text: text},
// Select the language and SSML Voice Gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// Select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
exports.getAudiocast = functions.https.onCall((data, context) => {
var bucket = storage.bucket('gs://[project-name].appspot.com/content/feeds/en-audio/');
client.synthesizeSpeech(request, (err, response) => {
if (err) {
console.error('ERROR:', err);
return;
}
const tempFile = path.join(os.tmpdir(), (data.id + '.mp3'));
fs.writeFile(tempFile, response.auioContent, 'binary', err => {
if (err) {
console.error('ERROR:', err);
return;
}
console.log('Audio content written to file: ' + tempFile);
bucket.upload(tempFile), function(err, file) {
if (!err) {
console.log('Audiocast uploaded!');
} else {
console.error('Audiocast upload error: ' + err.message);
}
};
});
});
return {
filePath: "cloudStorage/someFilePath",
};
});
Следующий шагЯ попытаюсь загрузить обычный текстовый файл вместо двоичного файла, чтобы увидеть, является ли временный формат файла проблемой.