114 lines
2.8 KiB
Java
114 lines
2.8 KiB
Java
package me.mctp.radio;
|
|
|
|
import com.mpatric.mp3agic.InvalidDataException;
|
|
import com.mpatric.mp3agic.UnsupportedTagException;
|
|
import me.mctp.Main;
|
|
import me.mctp.managers.PinManager;
|
|
import me.mctp.utils.HeadUtil;
|
|
import org.bukkit.Bukkit;
|
|
import org.bukkit.entity.Player;
|
|
import org.bukkit.scheduler.BukkitTask;
|
|
import org.json.simple.JSONObject;
|
|
|
|
import java.io.IOException;
|
|
|
|
public class Playlist {
|
|
private me.mctp.api.maps.Playlist<String> songList = new me.mctp.api.maps.Playlist<>();
|
|
private boolean running = false;
|
|
private BukkitTask currentTimer;
|
|
|
|
/**
|
|
* Init, load all the songs from the data and start first
|
|
*/
|
|
public Playlist() {
|
|
init();
|
|
}
|
|
|
|
/**
|
|
* Load the songs into the system and start
|
|
*/
|
|
public void init() {
|
|
for (String URL : Main.getPlugin().getConfig().getStringList("RadioSongs")) {
|
|
addSong(URL);
|
|
}
|
|
|
|
Bukkit.getScheduler().runTaskAsynchronously(Main.getPlugin(), this::nextSong);
|
|
|
|
running = true;
|
|
}
|
|
|
|
/**
|
|
* Stop the playlist (clears the queue)
|
|
*/
|
|
public void stop() {
|
|
songList.clear();
|
|
|
|
if (currentTimer != null) {
|
|
currentTimer.cancel();
|
|
currentTimer = null;
|
|
}
|
|
|
|
running = false;
|
|
}
|
|
|
|
/**
|
|
* Add a song by the url
|
|
* @param url The song url (mp3)
|
|
*/
|
|
public void addSong(String url) {
|
|
songList.add(url);
|
|
songList.shuffle();
|
|
}
|
|
|
|
/**
|
|
* Go to the next song
|
|
*/
|
|
public void nextSong() {
|
|
if (currentTimer != null) return;
|
|
|
|
//Get song
|
|
String nextURL = songList.getRandom();
|
|
if (nextURL == null) return;
|
|
|
|
JSONObject data;
|
|
for (Player p : Bukkit.getOnlinePlayers()) {
|
|
data = new JSONObject();
|
|
|
|
if (!PinManager.hasPin(p.getUniqueId())) continue;
|
|
|
|
data.put("task", "RADIO");
|
|
data.put("path", nextURL);
|
|
data.put("uuid", p.getUniqueId().toString().replace("-", ""));
|
|
Main.getClient().sendData(data);
|
|
}
|
|
|
|
int ticks;
|
|
try {
|
|
ticks = HeadUtil.getTicksOfFile(nextURL);
|
|
} catch (IOException | InvalidDataException | UnsupportedTagException e) {
|
|
e.printStackTrace();
|
|
nextSong();
|
|
return;
|
|
}
|
|
|
|
if (ticks == 0) {
|
|
Bukkit.getLogger().info("0 ticks");
|
|
nextSong();
|
|
return;
|
|
}
|
|
|
|
Bukkit.getLogger().info("Started song with duration: " + ticks/20 + " sec.");
|
|
|
|
currentTimer = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getPlugin(), () -> {
|
|
currentTimer = null;
|
|
nextSong();
|
|
}, ticks);
|
|
|
|
//Shuffle playlist again
|
|
songList.shuffle();
|
|
}
|
|
|
|
public boolean isRunning() {
|
|
return running;
|
|
}
|
|
}
|