I want to create a music feature for my discord bot that can stream audio from YouTube and other sources. Right now I’m just testing with a local audio file to make sure the basic functionality works before I tackle the more complex streaming parts.
(node:12345) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'voiceConnection' before initialization
at /home/user/mybot/bot.js:156:28
at processTicksAndRejections (internal/process/task_queues.js:97:5)
What am I doing wrong with the connection setup? The bot joins the voice channel but crashes when trying to play the audio file.
Your problem’s with variable scoping in the promise chain. You’re declaring voiceConnection with const but trying to assign it inside a .then() callback - that creates a reference error since the variable isn’t initialized in that scope. I’ve hit the same issue working on voice features. Just restructure to avoid mixing promise patterns:
This ditches the problematic .then() chain and uses async/await throughout. Double-check your file path’s correct and you’ve got the voice dependencies installed.
your promise handling’s broken - you’re mixing async/await with .then() and it’s causing scope issues. the voiceconnection variable can’t be accessed inside that then block. just await the join() call directly, then use the connection object it returns to play audio. also check that your discord.js voice dependencies are installed right or you’ll hit more weird errors.
Your promise chain structure is the problem. When you use .then() after join(), the voiceConnection variable doesn’t get the actual connection object. You’re trying to access it in the then block where it’s still undefined.
I hit this exact issue building my first music bot last year. Fix it by handling the promise resolution properly. Either use async/await correctly or fix the promise chain:
Or if you want promise syntax, move the variable declaration inside the then block. Make sure the connection’s fully established before playing audio. Also check that your audio file path is correct relative to your bot’s working directory.