Twitch embed getPlayer method undefined error

I’m trying to integrate a Twitch video player into my website but running into some issues. When I create the embed and try to access the player object, I get an error saying the getPlayer method doesn’t exist.

Here’s my current code:

var twitchEmbed = new Twitch.Embed("stream-container", {
    width: 720,
    height: 405,
    channel: "ninja",
    layout: "video",
    autoplay: false
});

var streamPlayer = twitchEmbed.getPlayer();
streamPlayer.addEventListener(Twitch.Player.PLAY, function() {
    updateBannerContent();
});
streamPlayer.play();

The weird thing is that even though I set autoplay to false, the stream starts playing automatically anyway. Has anyone encountered this problem before? I’m not sure if I’m missing something or if there’s a timing issue with when the player becomes available.

Yeah, this is a timing issue. The Twitch embed doesn’t have the player object ready when you call getPlayer() right after creating it. I hit this exact problem building a streaming dashboard last year. You’ve got to wait for the embed to load first. Use the ready event: twitchEmbed.addEventListener('ready', function() { var player = twitchEmbed.getPlayer(); }) then put your event listeners inside that callback. For autoplay - Twitch ignores that setting sometimes because of browser autoplay policies. If you want it stopped initially, call pause() after the player’s ready.