7
10

More than 1 year has passed since last update.

discord.jsで音声合成機能を作る

Last updated at Posted at 2021-03-27

今回つくるもの

1.discord 上で読み上げるテキストを指定するコマンドを実行
2.メッセージから読みあげたいテキストを取得
3.Google の TTSAPI にリクエスト送信
4.結果を取得
5.1が送信されたチャンネルに結果を送信

必要なもの

・@replit/node-fetch(npm i @replit/node-fetch)
・stream(npm i stream)
・util(npm i util)
・discord.js(npm i discord.js);
discord.js の実行環境の整備は、ここでは省きます。

コード

const prefix = "!";
const discord = require("discord.js");
const { createWriteStream } = require("fs");
const { pipeline } = require("stream");
const { promisify } = require("util");
const fetch = require("@replit/node-fetch");
const client = new discord.Client({
  intents: [
    discord.GatewayIntentBits.Guilds,
    discord.GatewayIntentBits.GuildMessages,
    discord.GatewayIntentBits.MessageContent,
  ],
});

client.on(discord.Events.MessageCreate, async (message) => {
  if (message.author.bot) return;
  const args = message.content.slice(prefix.length).trim().split(/ +/g);
  const command = args.shift().toLowerCase();
  if (command == "voicetext") {
    const t = args.join(" ");
    const m = Math.random().toString(36).slice(2, 12);
    const streamPipeline = promisify(pipeline);

    const response = await fetch(
      `https://www.google.com/speech-api/v1/synthesize?text=${encodeURI(
        t
      )}&nc=mpeg&lang=ja&speed=0.5&client=lr-language-tts`
    );

    if (!response.ok)
      throw new Error(`unexpected response ${response.statusText}`);

    await streamPipeline(response.body, createWriteStream(`./voices/${m}.mp3`));
    message.channel.send({ content: "結果:", files: [`voices/${m}.mp3`] });
  }
});
client.login("token");

結果

!voicetext <text>を実行すると、音声合成した結果が返ってきます!
スクリーンショット 2021-03-27 174757.png

7
10
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10