Reformat code.
This commit is contained in:
parent
b8b7a99a8d
commit
ed610ebdae
|
@ -38,34 +38,34 @@ import net.dv8tion.jda.api.utils.cache.CacheFlag;
|
|||
public class Main extends ListenerAdapter
|
||||
{
|
||||
|
||||
/**
|
||||
* @param args the command line arguments
|
||||
*/
|
||||
public static void main(String[] args) throws LoginException
|
||||
{
|
||||
// We only need 2 gateway intents enabled for this example:
|
||||
/**
|
||||
* @param args the command line arguments
|
||||
*/
|
||||
public static void main(String[] args) throws LoginException
|
||||
{
|
||||
// We only need 2 gateway intents enabled for this example:
|
||||
EnumSet<GatewayIntent> intents = EnumSet.of(
|
||||
// We need messages in guilds to accept commands from users
|
||||
GatewayIntent.GUILD_MESSAGES,
|
||||
// We need voice states to connect to the voice channel
|
||||
GatewayIntent.GUILD_VOICE_STATES
|
||||
// We need messages in guilds to accept commands from users
|
||||
GatewayIntent.GUILD_MESSAGES,
|
||||
// We need voice states to connect to the voice channel
|
||||
GatewayIntent.GUILD_VOICE_STATES
|
||||
);
|
||||
|
||||
JDABuilder builder = JDABuilder.createDefault(args[0], intents);
|
||||
JDABuilder builder = JDABuilder.createDefault(args[0], intents);
|
||||
|
||||
// Disable parts of the cache
|
||||
builder.disableCache(CacheFlag.MEMBER_OVERRIDES, CacheFlag.VOICE_STATE);
|
||||
// Enable the bulk delete event
|
||||
builder.setBulkDeleteSplittingEnabled(false);
|
||||
// Disable compression (not recommended)
|
||||
builder.setCompression(Compression.NONE);
|
||||
// Set activity (like "playing Something")
|
||||
builder.setActivity(Activity.playing("music!"));
|
||||
// Disable parts of the cache
|
||||
builder.disableCache(CacheFlag.MEMBER_OVERRIDES, CacheFlag.VOICE_STATE);
|
||||
// Enable the bulk delete event
|
||||
builder.setBulkDeleteSplittingEnabled(false);
|
||||
// Disable compression (not recommended)
|
||||
builder.setCompression(Compression.NONE);
|
||||
// Set activity (like "playing Something")
|
||||
builder.setActivity(Activity.playing("music!"));
|
||||
|
||||
builder.addEventListeners(new Main());
|
||||
builder.addEventListeners(new Main());
|
||||
|
||||
JDA jda = builder.build();
|
||||
}
|
||||
JDA jda = builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGuildMessageReceived(GuildMessageReceivedEvent event)
|
||||
|
@ -83,23 +83,20 @@ public class Main extends ListenerAdapter
|
|||
{
|
||||
String arg = content.substring("!join ".length());
|
||||
onJoinCommand(event, guild, arg);
|
||||
}
|
||||
else if (content.equals("!join"))
|
||||
{
|
||||
} else if (content.equals("!join"))
|
||||
onJoinCommand(event);
|
||||
else if (content.startsWith("!play "))
|
||||
{
|
||||
String arg = content.substring("!join ".length());
|
||||
onPlayCommand(event, guild, arg);
|
||||
}
|
||||
else if (content.startsWith("!play "))
|
||||
{
|
||||
String arg = content.substring("!join ".length());
|
||||
onPlayCommand(event, guild, arg);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle command without arguments.
|
||||
*
|
||||
* @param event
|
||||
* The event for this command
|
||||
* The event for this command
|
||||
*/
|
||||
private void onJoinCommand(GuildMessageReceivedEvent event)
|
||||
{
|
||||
|
@ -111,31 +108,27 @@ public class Main extends ListenerAdapter
|
|||
{
|
||||
connectTo(channel); // Join the channel of the user
|
||||
onConnecting(channel, event.getChannel()); // Tell the user about our success
|
||||
}
|
||||
else
|
||||
{
|
||||
} else
|
||||
onUnknownChannel(event.getChannel(), "your voice channel"); // Tell the user about our failure
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle command with arguments.
|
||||
*
|
||||
* @param event
|
||||
* The event for this command
|
||||
* The event for this command
|
||||
* @param guild
|
||||
* The guild where its happening
|
||||
* The guild where its happening
|
||||
* @param arg
|
||||
* The input argument
|
||||
* The input argument
|
||||
*/
|
||||
private void onJoinCommand(GuildMessageReceivedEvent event, Guild guild, String arg)
|
||||
{
|
||||
boolean isNumber = arg.matches("\\d+"); // This is a regular expression that ensures the input consists of digits
|
||||
VoiceChannel channel = null;
|
||||
if (isNumber) // The input is an id?
|
||||
{
|
||||
if (isNumber) // The input is an id?
|
||||
|
||||
channel = guild.getVoiceChannelById(arg);
|
||||
}
|
||||
if (channel == null) // Then the input must be a name?
|
||||
{
|
||||
List<VoiceChannel> channels = guild.getVoiceChannelsByName(arg, true);
|
||||
|
@ -153,48 +146,47 @@ public class Main extends ListenerAdapter
|
|||
onConnecting(channel, textChannel); // Let the user know, we were successful!
|
||||
}
|
||||
|
||||
private void onPlayCommand(GuildMessageReceivedEvent event, Guild guild, String arg)
|
||||
{
|
||||
try
|
||||
{
|
||||
event.getChannel().sendMessage("Downloading ...").queue();
|
||||
String destination = downloadSong(arg);
|
||||
musicHandler.addSong(new File(destination));
|
||||
event.getChannel().sendMessage("Downloaded and added to queue!").queue();
|
||||
private void onPlayCommand(GuildMessageReceivedEvent event, Guild guild, String arg)
|
||||
{
|
||||
try
|
||||
{
|
||||
event.getChannel().sendMessage("Downloading ...").queue();
|
||||
String destination = downloadSong(arg);
|
||||
musicHandler.addSong(new File(destination));
|
||||
event.getChannel().sendMessage("Downloaded and added to queue!").queue();
|
||||
|
||||
} catch (IOException | InterruptedException | RuntimeException ex)
|
||||
{
|
||||
event.getChannel().sendMessage("Failed to download! Reason: " + ex.getMessage()).queue();
|
||||
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
||||
}
|
||||
}
|
||||
} catch (IOException | InterruptedException | RuntimeException ex)
|
||||
{
|
||||
event.getChannel().sendMessage("Failed to download! Reason: " + ex.getMessage()).queue();
|
||||
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
||||
}
|
||||
}
|
||||
|
||||
private String downloadSong(String arg) throws IOException, RuntimeException, InterruptedException
|
||||
{
|
||||
String cmd = "/usr/bin/youtube-dl -x --audio-format=wav "+arg;
|
||||
System.out.println("Running command: " + cmd);
|
||||
private String downloadSong(String arg) throws IOException, RuntimeException, InterruptedException
|
||||
{
|
||||
String cmd = "/usr/bin/youtube-dl -x --audio-format=wav " + arg;
|
||||
System.out.println("Running command: " + cmd);
|
||||
// Process exec = Runtime.getRuntime().exec().split(" "));
|
||||
Process exec = new ProcessBuilder(cmd.split(" ")).redirectOutput(ProcessBuilder.Redirect.PIPE).start();
|
||||
exec.waitFor(10000, TimeUnit.MILLISECONDS);
|
||||
InputStream in = exec.getInputStream();
|
||||
String output = new String(in.readAllBytes(), Charset.defaultCharset());
|
||||
System.out.println(output);
|
||||
if (exec.exitValue() != 0)
|
||||
throw new RuntimeException("youtube-dl failed with error " + exec.exitValue());
|
||||
Matcher matcher = Pattern.compile("Destination: (.*\\.wav)").matcher(output);
|
||||
matcher.find();
|
||||
String destination = matcher.group(1);
|
||||
return destination;
|
||||
}
|
||||
|
||||
Process exec = new ProcessBuilder(cmd.split(" ")).redirectOutput(ProcessBuilder.Redirect.PIPE).start();
|
||||
exec.waitFor(10000, TimeUnit.MILLISECONDS);
|
||||
InputStream in = exec.getInputStream();
|
||||
String output = new String(in.readAllBytes(), Charset.defaultCharset());
|
||||
System.out.println(output);
|
||||
if (exec.exitValue() != 0)
|
||||
throw new RuntimeException("youtube-dl failed with error " + exec.exitValue());
|
||||
Matcher matcher = Pattern.compile("Destination: (.*\\.wav)").matcher(output);
|
||||
matcher.find();
|
||||
String destination = matcher.group(1);
|
||||
return destination;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inform user about successful connection.
|
||||
*
|
||||
* @param channel
|
||||
* The voice channel we connected to
|
||||
* The voice channel we connected to
|
||||
* @param textChannel
|
||||
* The text channel to send the message in
|
||||
* The text channel to send the message in
|
||||
*/
|
||||
private void onConnecting(VoiceChannel channel, TextChannel textChannel)
|
||||
{
|
||||
|
@ -205,9 +197,10 @@ public class Main extends ListenerAdapter
|
|||
* The channel to connect to is not known to us.
|
||||
*
|
||||
* @param channel
|
||||
* The message channel (text channel abstraction) to send failure information to
|
||||
* The message channel (text channel abstraction) to send failure
|
||||
* information to
|
||||
* @param comment
|
||||
* The information of this channel
|
||||
* The information of this channel
|
||||
*/
|
||||
private void onUnknownChannel(MessageChannel channel, String comment)
|
||||
{
|
||||
|
@ -218,19 +211,18 @@ public class Main extends ListenerAdapter
|
|||
* Connect to requested channel and start echo handler
|
||||
*
|
||||
* @param channel
|
||||
* The channel to connect to
|
||||
* The channel to connect to
|
||||
*/
|
||||
private void connectTo(VoiceChannel channel)
|
||||
{
|
||||
Guild guild = channel.getGuild();
|
||||
// Get an audio manager for this guild, this will be created upon first use for each guild
|
||||
AudioManager audioManager = guild.getAudioManager();
|
||||
musicHandler = new MusicHandler();
|
||||
musicHandler = new MusicHandler();
|
||||
// Create our Send/Receive handler for the audio connection
|
||||
// EchoHandler handler = new EchoHandler();
|
||||
|
||||
// The order of the following instructions does not matter!
|
||||
|
||||
// Set the sending handler to our echo system
|
||||
audioManager.setSendingHandler(musicHandler);
|
||||
// Set the receiving handler to the same echo system, otherwise we can't echo anything
|
||||
|
@ -238,6 +230,6 @@ public class Main extends ListenerAdapter
|
|||
// Connect to the voice channel
|
||||
audioManager.openAudioConnection(channel);
|
||||
}
|
||||
private MusicHandler musicHandler;
|
||||
private MusicHandler musicHandler;
|
||||
|
||||
}
|
||||
|
|
|
@ -26,115 +26,115 @@ import net.dv8tion.jda.api.audio.AudioSendHandler;
|
|||
public class MusicHandler implements AudioSendHandler, Closeable
|
||||
{
|
||||
|
||||
private final Queue<File> songQueue = new ConcurrentLinkedQueue<>();
|
||||
private File currentSong;
|
||||
private AudioInputStream din = null;
|
||||
private final Queue<byte[]> queue = new ConcurrentLinkedQueue<>();
|
||||
private int byteCount;
|
||||
private final Queue<File> songQueue = new ConcurrentLinkedQueue<>();
|
||||
private File currentSong;
|
||||
private AudioInputStream din = null;
|
||||
private final Queue<byte[]> queue = new ConcurrentLinkedQueue<>();
|
||||
private int byteCount;
|
||||
|
||||
public MusicHandler()
|
||||
{
|
||||
}
|
||||
public MusicHandler()
|
||||
{
|
||||
}
|
||||
|
||||
public void addSong(File file)
|
||||
{
|
||||
System.out.println("Song added to queue: " + file.getAbsolutePath());
|
||||
songQueue.add(file);
|
||||
if (!canProvide())
|
||||
nextSong();
|
||||
}
|
||||
public void addSong(File file)
|
||||
{
|
||||
System.out.println("Song added to queue: " + file.getAbsolutePath());
|
||||
songQueue.add(file);
|
||||
if (!canProvide())
|
||||
nextSong();
|
||||
}
|
||||
|
||||
private boolean nextSong()
|
||||
{
|
||||
AudioInputStream in = null;
|
||||
try
|
||||
{
|
||||
if (din != null)
|
||||
{
|
||||
din.close();
|
||||
din = null;
|
||||
}
|
||||
if (currentSong != null)
|
||||
{
|
||||
currentSong.delete();
|
||||
currentSong = null;
|
||||
}
|
||||
currentSong = songQueue.poll();
|
||||
if (currentSong == null)
|
||||
return false;
|
||||
System.out.println("Playing song " + currentSong.getAbsolutePath());
|
||||
in = AudioSystem.getAudioInputStream(currentSong);
|
||||
AudioFormat decodedFormat = AudioSendHandler.INPUT_FORMAT;
|
||||
din = AudioSystem.getAudioInputStream(decodedFormat, in);
|
||||
byteCount = 3840;
|
||||
while (queue.size() < 500)
|
||||
if (!readData())
|
||||
break;
|
||||
System.out.println("Queue filled to " + queue.size());
|
||||
return true;
|
||||
} catch (UnsupportedAudioFileException | IOException ex)
|
||||
{
|
||||
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
||||
} finally
|
||||
{
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private boolean nextSong()
|
||||
{
|
||||
AudioInputStream in = null;
|
||||
try
|
||||
{
|
||||
if (din != null)
|
||||
{
|
||||
din.close();
|
||||
din = null;
|
||||
}
|
||||
if (currentSong != null)
|
||||
{
|
||||
currentSong.delete();
|
||||
currentSong = null;
|
||||
}
|
||||
currentSong = songQueue.poll();
|
||||
if (currentSong == null)
|
||||
return false;
|
||||
System.out.println("Playing song " + currentSong.getAbsolutePath());
|
||||
in = AudioSystem.getAudioInputStream(currentSong);
|
||||
AudioFormat decodedFormat = AudioSendHandler.INPUT_FORMAT;
|
||||
din = AudioSystem.getAudioInputStream(decodedFormat, in);
|
||||
byteCount = 3840;
|
||||
while (queue.size() < 500)
|
||||
if (!readData())
|
||||
break;
|
||||
System.out.println("Queue filled to " + queue.size());
|
||||
return true;
|
||||
} catch (UnsupportedAudioFileException | IOException ex)
|
||||
{
|
||||
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
||||
} finally
|
||||
{
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canProvide()
|
||||
{
|
||||
// If we have something in our buffer we can provide it to the send system
|
||||
return !queue.isEmpty();
|
||||
}
|
||||
@Override
|
||||
public boolean canProvide()
|
||||
{
|
||||
// If we have something in our buffer we can provide it to the send system
|
||||
return !queue.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ByteBuffer provide20MsAudio()
|
||||
{
|
||||
// use what we have in our buffer to send audio as PCM
|
||||
while (queue.size() < 500)
|
||||
if (!readData())
|
||||
if (!nextSong())
|
||||
break;
|
||||
byte[] data = queue.poll();
|
||||
return data == null ? null : ByteBuffer.wrap(data); // Wrap this in a java.nio.ByteBuffer
|
||||
}
|
||||
@Override
|
||||
public ByteBuffer provide20MsAudio()
|
||||
{
|
||||
// use what we have in our buffer to send audio as PCM
|
||||
while (queue.size() < 500)
|
||||
if (!readData())
|
||||
if (!nextSong())
|
||||
break;
|
||||
byte[] data = queue.poll();
|
||||
return data == null ? null : ByteBuffer.wrap(data); // Wrap this in a java.nio.ByteBuffer
|
||||
}
|
||||
|
||||
private boolean readData()
|
||||
{
|
||||
if (din == null)
|
||||
return false;
|
||||
try
|
||||
{
|
||||
// if (din.available() == 0)
|
||||
// return false;
|
||||
int bytesToRead = byteCount;
|
||||
if (din.available() > 0 && din.available() < bytesToRead)
|
||||
bytesToRead = din.available();
|
||||
byte[] bytes = new byte[bytesToRead];
|
||||
// byte[] bytes = din.readNBytes(bytesToRead);
|
||||
int read = din.read(bytes);
|
||||
if (read < 0)
|
||||
return false;
|
||||
queue.add(bytes);
|
||||
} catch (IOException ex)
|
||||
{
|
||||
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
private boolean readData()
|
||||
{
|
||||
if (din == null)
|
||||
return false;
|
||||
try
|
||||
{
|
||||
// if (din.available() == 0)
|
||||
// return false;
|
||||
int bytesToRead = byteCount;
|
||||
if (din.available() > 0 && din.available() < bytesToRead)
|
||||
bytesToRead = din.available();
|
||||
byte[] bytes = new byte[bytesToRead];
|
||||
// byte[] bytes = din.readNBytes(bytesToRead);
|
||||
int read = din.read(bytes);
|
||||
if (read < 0)
|
||||
return false;
|
||||
queue.add(bytes);
|
||||
} catch (IOException ex)
|
||||
{
|
||||
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOpus()
|
||||
{
|
||||
return false; //To change body of generated methods, choose Tools | Templates.
|
||||
}
|
||||
@Override
|
||||
public boolean isOpus()
|
||||
{
|
||||
return false; //To change body of generated methods, choose Tools | Templates.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
din.close();
|
||||
}
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
din.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue