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

Node.js使用TextToSpeechLongAudioSynthesizeClient报错,求正确用法示例

TextToSpeechLongAudioSynthesizeClient 正确使用示例(解决无效参数错误)

你的代码核心问题是:长文本语音合成API(Long Audio Synthesis)要求必须将输出文件写入Google Cloud Storage(GCS)路径,不能像普通TTS API那样直接获取audioContent返回本地。这就是你收到"Request contains an invalid argument"错误的原因。

以下是完整的正确使用示例:

const textToSpeech = require("@google-cloud/text-to-speech").v1;
const { Storage } = require("@google-cloud/storage");
const fs = require("fs");
const util = require("util");

// 初始化客户端
const ttsClient = new textToSpeech.TextToSpeechLongAudioSynthesizeClient();
const storageClient = new Storage();

async function synthesizeLongAudio() {
  try {
    const request = {
      input: { text: "这是一段用于长文本语音合成的测试内容" },
      // 必须指定支持长文本合成的语音模型
      voice: {
        languageCode: "en-US",
        name: "en-US-Neural2-J",
        ssmlGender: "MALE"
      },
      audioConfig: {
        audioEncoding: "MP3",
        speakingRate: 1.0,
        pitch: 0.0
      },
      // 必填:指定GCS输出路径,格式为 gs://<存储桶名称>/<输出文件名>
      outputGcsUri: "gs://your-bucket-name/output-long.mp3"
    };

    // 发起异步合成请求
    const [operation] = await ttsClient.synthesizeLongAudio(request);
    console.log("合成任务已提交,等待完成...");

    // 等待任务完成
    const [response] = await operation.promise();
    console.log("合成完成,输出路径:", response.outputGcsUri);

    // 可选:将GCS中的文件下载到本地
    const [file] = await storageClient.bucket("your-bucket-name").file("output-long.mp3").download();
    const writeFile = util.promisify(fs.writeFile);
    await writeFile("local-output.mp3", file, "binary");
    console.log("文件已下载到本地");
  } catch (err) {
    console.error("合成出错:", err);
  }
}

// 执行函数
synthesizeLongAudio();

关键注意事项:

  • 必填参数outputGcsUri:必须提供有效的GCS存储桶路径,否则直接报错无效参数
  • 权限配置:确保你的服务账号拥有以下权限:
    • roles/storage.objectCreator(写入GCS)
    • roles/texttospeech.synthesizer(调用TTS API)
  • 语音模型限制:必须使用支持长文本合成的模型,所有Neural2系列模型都支持,可参考官方模型列表确认
  • 长文本处理:如果要合成超长文本(比如超过10分钟),建议将文本上传到GCS,然后使用input.gcsSource替代input.text,示例:
    input: {
      gcsSource: {
        uri: "gs://your-bucket-name/long-text.txt"
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:35:20