package com.sedmelluq.discord.lavaplayer.demo.jda;

import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import net.dv8tion.jda.audio.AudioSendHandler;

/**
 * This is a wrapper around AudioPlayer which makes it behave as an AudioSendHandler for JDA. As JDA calls canProvide
 * before every call to provide20MsAudio(), we pull the frame in canProvide() and use the frame we already pulled in
 * provide20MsAudio().
 */
public class AudioPlayerSendHandler implements AudioSendHandler {
  private final AudioPlayer audioPlayer;
  private AudioFrame lastFrame;

  /**
   * @param audioPlayer Audio player to wrap.
   */
  public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
    this.audioPlayer = audioPlayer;
  }

  @Override
  public boolean canProvide() {
    lastFrame = audioPlayer.provide();
    return lastFrame != null;
  }

  @Override
  public byte[] provide20MsAudio() {
    return lastFrame.data;
  }

  @Override
  public boolean isOpus() {
    return true;
  }
}

@@ -824,24 +824,55 @@
 Provide() %7B%0A
+    if (lastFrame == null) %7B%0A  
     lastFram
@@ -898,16 +898,23 @@
 vide();%0A
+    %7D%0A%0A
     retu
@@ -985,24 +985,185 @@
 MsAudio() %7B%0A
+    if (lastFrame == null) %7B%0A      lastFrame = audioPlayer.provide();%0A    %7D%0A%0A    byte%5B%5D data = lastFrame != null ? lastFrame.data : null;%0A    lastFrame = null;%0A%0A
     return l
@@ -1161,26 +1161,16 @@
  return 
-lastFrame.
 data;%0A  

Make it safe to call canProvide multiple times (or not at all).