ThemeParkAudio/src/main/java/me/mctp/utils/HeadUtil.java
2020-11-16 18:52:42 +01:00

84 lines
2.5 KiB
Java

package me.mctp.utils;
import com.mpatric.mp3agic.InvalidDataException;
import com.mpatric.mp3agic.Mp3File;
import com.mpatric.mp3agic.UnsupportedTagException;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class HeadUtil {
public static String getArgument(String selector, String key) {
StringBuilder result = new StringBuilder();
String[] arguments = selector.split(key + "=");
if (arguments.length == 1) return "";
for (byte type : arguments[1].getBytes()) {
char element = (char) type;
if (element == ',' || element == ']') {
return result.toString();
} else {
result.append(element);
}
}
return result.toString().replaceAll("\\.", "");
}
private static String downloadFromUrl(URL url, String localFilename) throws IOException {
InputStream is = null;
FileOutputStream fos = null;
String tempDir = System.getProperty("java.io.tmpdir");
String outputPath = tempDir + "/" + localFilename;
try {
//connect
URLConnection urlConn = url.openConnection();
//get inputstream from connection
is = urlConn.getInputStream();
fos = new FileOutputStream(outputPath);
// 4KB buffer
byte[] buffer = new byte[4096];
int length;
// read from source and write into local file
while ((length = is.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
return outputPath;
} finally {
try {
if (is != null) {
is.close();
}
} finally {
if (fos != null) {
fos.close();
}
}
}
}
public static int getTicksOfFile(String input) throws IOException, InvalidDataException, UnsupportedTagException {
URL url = new URL(input);
String result = downloadFromUrl(url, FilenameUtils.getName(url.getPath()));
File file = new File(result);
if (!file.exists()) return 0;
Mp3File mp3File = new Mp3File(file);
long sec = mp3File.getLengthInSeconds();
file.delete();
return (int) (sec * 20);
}
}