Text-to-Speech Feature Not Working in Discord Bot

I’m working on a Discord bot and trying to implement a text-to-speech functionality. I installed the required package using npm install discord-tts but my voice command isn’t functioning properly. Here’s the code I’m using:

const voiceTTS = require("discord-tts");
const BaseCommand = require('../BaseCommand.js');

module.exports = class VoiceCommand extends BaseCommand {
    constructor(bot) {
        super(bot, {
            name: 'say',
            usage: 'say <text>',
            description: 'Converts text to speech in voice channel.',
            type: bot.types.ENTERTAINMENT
        });
    }

    async execute(msg, arguments) {
        function textToSpeech(voiceChan, message) {
            const audioBroadcast = client.voice.createBroadcast();
            var chanId = msg.member.voice.channelID;
            var voiceRoom = client.channels.cache.get(chanId);
            voiceRoom.join().then(conn => {
                audioBroadcast.play(voiceTTS.getVoiceStream(arguments));
                const audioDispatcher = conn.play(audioBroadcast);
            });
        }
    }
}

I’ve tried multiple approaches but can’t get it working. What could be missing from my implementation?

Your code defines the textToSpeech function but never calls it. Add textToSpeech() at the end of your execute method. Also spotted a few other issues: you’re using client inside the function when it should be this.bot, or you need to pass the client properly. Check if the user’s actually in a voice channel before trying to join - I ran into this same problem when I first set up TTS. The discord-tts package gets weird with certain text inputs, so throw in some basic validation on the arguments before feeding them to getVoiceStream. That should fix your immediate problem.

you’re missing the actual function call and error handling. add await textToSpeech() after defining it, and check if arguments isn’t empty before passing it to getVoiceStream. also, if you’re using discord.js v13+, you’ll need @discordjs/voice instead of the old voice methods.

Your code has a scope problem - you’re calling client inside textToSpeech but it’s not defined there. Either pass it as a parameter or use this.bot since you’re extending BaseCommand. Also, discord-tts is deprecated and breaks with newer Discord.js versions. I switched to Google’s text-to-speech API (@google-cloud/text-to-speech) about a year ago - way more reliable. Setup’s trickier but worth it. If you stick with your current setup, make sure you handle voice connections properly and add error catching around the join operation. Voice channels are finicky.