基于Java實現(xiàn)音樂播放器的示例代碼
Java音樂播放器
這里利用了一個我覺得挺不錯的音樂網(wǎng)站
歌曲資源全來自于那里
然后mp3播放jar使用的為jl1.0.jar
來自音樂網(wǎng)站上的歌曲一般為m4a格式,所以我們需要一個轉(zhuǎn)碼工具,可以使用ffmpeg進行轉(zhuǎn)碼,這里我用的是jave-1.0.2.jar,它是一個封裝了linux和windows通用版本的ffmpeg
WebGet.java用于獲取網(wǎng)站資源
package youget;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import youget.allProperty.douyins;
import youget.allProperty.putong;
public class WebGet {
public static String getrealurl(String str)
{
HttpURLConnection httpURLConnection;
HttpsURLConnection conn;
try {
URL url = new URL(str);
trustAllHosts();
if (url.getProtocol().toLowerCase().equals("https")) {
conn=(HttpsURLConnection)url.openConnection();
conn.setHostnameVerifier(DO_NOT_VERIFY);
httpURLConnection=conn;
}//不驗證主機證書
else
httpURLConnection=(HttpURLConnection)url.openConnection();
douyins d=new allProperty().new douyins();
d.setProperty(httpURLConnection);
String urls=httpURLConnection.getHeaderField("location");
System.out.println("跳轉(zhuǎn)至:"+urls);
httpURLConnection.disconnect();
return urls;
} catch (MalformedURLException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
return null;
}
public static void search(String name,List<PT> outs)
{
String html="https://www.hifini.com/search-";
String t=null;
try {
t = URLEncoder.encode(name, "utf-8");
t=t.replace('%', '_');
html+=t;
t=null;
html+=".htm";
} catch (UnsupportedEncodingException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
putong d=new allProperty().new putong();
t=get_https(html, d, 200, false, false);
List<String> all=findall(t,"<a href=\"thread-","</a>");
t=null;
for(String i:all)
{
String h[]=i.split(".htm\">");
h[1]=h[1].replaceAll("<span class=\"text-danger\">", "");
h[1]=h[1].replaceAll("</span>", "");
PT ts=new PT(h[1],"https://www.hifini.com/thread-"+h[0]+".htm");
outs.add(ts);
}
}
public static List<String> findall(String code,String starts,String ends)
{
List<String> temp=new ArrayList<String>();
int start=0;
int end=0;
while(true)
{
start=code.indexOf(starts,end);
if(start==-1)
break;
start+=starts.length();
end=code.indexOf(ends,start);
temp.add(code.substring(start,end));
end+=ends.length();
}
return temp;
}
private static String path="F:\\desktop\\1.m4a";
public static void you_get(String url,String filepath)
{
String urls=getmusicurl(url);
// System.out.print(urls);
// if(true)
// return;
download(urls, filepath);
}
public static String getmusicurl(String url)
{
putong d=new allProperty().new putong();
String html=get_https(url,d,200,true,false);
d=null;
int start=html.indexOf("url: \'")+6;
int end=html.indexOf("\'", start);
String h=html.substring(start, end);
html=null;
//System.out.println(h);
if(h.charAt(0)=='h')
{
try {
String k[]=h.split("music/");
k[0]+="music/";
h=URLEncoder.encode(k[1], "utf-8");
//h=h.replaceAll("+", "%20");
h=k[0]+h;
k=null;
h=h.replace("+", "%20");
} catch (UnsupportedEncodingException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
return h;
}
else
return "https://www.hifini.com/"+h;
}
public static void download(String url,String filepath)
{
if(filepath!=null)
path=filepath;
douyins d=new allProperty().new douyins();
WebGet.get_https(url,d,200,false,true);
d=null;
}
public static String get_https(String urls,Property pro,int tag,boolean flag,boolean download)
{
HttpURLConnection https;
HttpsURLConnection httpssl;
try {
URL url = new URL(urls);
trustAllHosts();//信任所有的主機
if (url.getProtocol().toLowerCase().equals("https")) {
httpssl=(HttpsURLConnection) url.openConnection();
httpssl.setHostnameVerifier(DO_NOT_VERIFY);//不驗證主機證書
https=httpssl;
}
else
https=(HttpURLConnection) url.openConnection();
https.setRequestMethod("GET");
pro.setProperty(https);
https.setConnectTimeout(2000);
int ttts=https.getResponseCode();
if(ttts==302)
{
return get_https(getrealurl(urls), pro, tag, flag, download);
}
else if(ttts!=404&&ttts!=502)
{
InputStream IS=https.getInputStream();
byte[] bt=new byte[1024];
int len=0;
FileOutputStream ttt = null;
if(download)
{
System.out.println("開始下載:"+urls);
ttt=new FileOutputStream(path);
}
ByteArrayOutputStream BS=new ByteArrayOutputStream();
int all=0;
while((len=IS.read(bt))!=-1)
{
if(flag)
{
if(all>6144)
{
BS.write(bt, 0, len);
}
all+=len;
if(all>8192)
break;
}
else
{
BS.write(bt, 0, len);
}
if(download)
ttt.write(bt,0,len);
}
IS.close();
if(download)
{
ttt.close();
return null;
}
String h=new String(BS.toByteArray(),"UTF-8");
BS.close();
BS=null;
return h;
}
else
{
System.out.println("error:"+urls);
throw new Exception("連接服務(wù)器失??!");
}
} catch (Exception e) {
// TODO 自動生成的 catch 塊
System.out.println(path);
e.printStackTrace();
}
return null;
}
public static void trustAllHosts() {
final String TAG = "trustAllHosts";
// 閸掓稑緙撴穱鈥叉崲緇狅紕鎮(zhèn)婇崳錕?
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//System.out.println(TAG+"checkClientTrusted");
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//System.out.println(TAG+"checkServerTrusted");
}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
//e.printStackTrace();
}
}
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
}Property.java用于提供網(wǎng)站請求頭接口
package youget;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
public interface Property {
public abstract void setProperty(HttpsURLConnection https);
public abstract void setProperty(HttpURLConnection https);
}PT.java用于儲存得到的標題和資源鏈接
package youget;
public class PT {
public String title,url;
public PT(String title,String url) {this.title=title;this.url=url;}
}allProperty.java用于提供http請求頭
package youget;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
public class allProperty {
public class douyins implements Property {
@Override
public void setProperty(HttpsURLConnection https) {
// TODO 自動生成的方法存根
https.setRequestProperty("Connection", "keep-alive");
https.setRequestProperty("sec-ch-ua",
"\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"");
https.setRequestProperty("sec-ch-ua-mobile", "?0");
https.setRequestProperty("Upgrade-Insecure-Requests", "1");
https.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
https.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
https.setRequestProperty("Sec-Fetch-Site", "none");
https.setRequestProperty("Sec-Fetch-Mode", "navigate");
https.setRequestProperty("Sec-Fetch-User", "?1");
https.setRequestProperty("Sec-Fetch-Dest", "document");
https.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
}
@Override
public void setProperty(HttpURLConnection https) {
// TODO 自動生成的方法存根
https.setRequestProperty("Connection", "keep-alive");
https.setRequestProperty("sec-ch-ua",
"\" Not;A Brand\";v=\"99\", \"Google Chrome\";v=\"91\", \"Chromium\";v=\"91\"");
https.setRequestProperty("sec-ch-ua-mobile", "?0");
https.setRequestProperty("Upgrade-Insecure-Requests", "1");
https.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
https.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
https.setRequestProperty("Sec-Fetch-Site", "none");
https.setRequestProperty("Sec-Fetch-Mode", "navigate");
https.setRequestProperty("Sec-Fetch-User", "?1");
https.setRequestProperty("Sec-Fetch-Dest", "document");
https.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
}
}
public class putong implements Property {
@Override
public void setProperty(HttpsURLConnection https) {
// TODO 自動生成的方法存根
https.setRequestProperty("Connection", "keep-alive");
https.setRequestProperty("Cache-Control", "max-age=0");
https.setRequestProperty("Upgrade-Insecure-Requests", "1");
https.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
https.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
// https.setRequestProperty("Accept-Encoding","gzip, deflate");
https.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
}
@Override
public void setProperty(HttpURLConnection https) {
// TODO 自動生成的方法存根
https.setRequestProperty("Connection", "keep-alive");
https.setRequestProperty("Cache-Control", "max-age=0");
https.setRequestProperty("Upgrade-Insecure-Requests", "1");
https.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
https.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
// https.setRequestProperty("Accept-Encoding","gzip, deflate");
https.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
}
}
}最后是Main.java顯示窗口
package youget;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;
import it.sauronsoftware.jave.MultimediaInfo;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
public class MyMain {
private static Timer timer;
private static TimerTask task;
private static long min1, min2, musictime, nowplaytime;
private static Player player;
private static FileInputStream openmusicfile;
private static boolean playing, playmusic, jslset;
private static String savepath = "F:\\desktop", playpath;
static String musicformat[]= {".m4a",".mp3",".mp2",".wav"};
public static boolean ismusic(String name)
{
for(String h:musicformat)
{
if(name.indexOf(h)!=-1)return true;
}
return false;
}
public static void main(String[] args) {
playing = false;
playmusic = false;
jslset = false;
File fp = new File("path.txt");
if (!fp.exists()) {
try {
FileOutputStream fo = new FileOutputStream(fp);
fo.write(savepath.getBytes());
fo.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
try {
FileInputStream fi = new FileInputStream(fp);
byte tss[] = new byte[256];
fi.read(tss);
fi.close();
int len = 0;
for (int i = 0; i < 256; i++) {
if (tss[i] == 0)
break;
len++;
}
savepath = new String(tss, 0, len);
tss = null;
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
List<PT> t = new ArrayList<PT>();
JFrame jf = new JFrame("hifini");
jf.setIconImage(new ImageIcon(MyMain.class.getResource("logo.png")).getImage());
jf.setBounds(0, 0, 600, 600);
jf.setResizable(false);
jf.setLayout(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
DefaultListModel<String> dlm = new DefaultListModel<String>();
JList jl = new JList();
jl.setModel(dlm);
jl.setFixedCellHeight(40);
jl.setCellRenderer(new DefaultListCellRenderer() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(238, 238, 238));
g.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);
}
});
jl.setSelectionBackground(new Color(7, 188, 252, 150));
jl.setBounds(0, 0, 575, 400);
JScrollPane js = new JScrollPane(jl);
jf.add(js);
js.setBounds(10, 60, 575, 400);
JTextField jt = new JTextField();
jt.setBounds(6, 15, 500, 30);
jf.add(jt);
JButton jb = new JButton("搜索");
jb.setBounds(510, 6, 75, 40);
jf.add(jb);
JLabel ja = new JLabel("就緒!");
JButton down = new JButton("下載");
down.setBounds(30, 510, 60, 40);
JSlider jsl = new JSlider();
JLabel showtime = new JLabel("00:00/00:00", JLabel.CENTER);
jl.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getButton()!=MouseEvent.BUTTON1)
return;
if (!playing)
return;
min1 = System.currentTimeMillis();
if (min1 - min2 < 500) {
int h = jl.getSelectedIndex();
if (!playmusic)
down.setText("停止");
playmusic = true;
PT ts = t.get(h);
changefile cf = new changefile(t, ts, ja, showtime, jsl, down, dlm, h);
new Thread(cf).start();
}
min2 = min1;
}
});
jb.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
if (playing) {
down.setText("下載");
playing = false;
}
t.clear();
dlm.clear();
String name = jt.getText().toString();
ja.setText("正在搜索:" + name);
jb.setEnabled(false);
new Thread(new Runnable() {
@Override
public void run() {
WebGet.search(name, t);
for (int i = 0; i < t.size(); i++) {
PT tk = t.get(i);
int x = tk.title.indexOf("[");
if (x != -1) {
tk.title = tk.title.substring(0, x);
t.set(i, tk);
}
}
for (PT tk : t) {
dlm.addElement(tk.title);
}
jb.setEnabled(true);
ja.setText("搜索:" + t.size() + "條結(jié)果");
}
}).start();
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
});
jt.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
t.clear();
dlm.clear();
String name = jt.getText().toString();
ja.setText("正在搜索:" + name);
jb.setEnabled(false);
new Thread(new Runnable() {
@Override
public void run() {
WebGet.search(name, t);
for (int i = 0; i < t.size(); i++) {
PT tk = t.get(i);
int x = tk.title.indexOf("[");
if (x != -1) {
tk.title = tk.title.substring(0, x);
t.set(i, tk);
}
}
for (PT tk : t) {
dlm.addElement(tk.title);
}
jb.setEnabled(true);
ja.setText("搜索:" + t.size() + "條結(jié)果");
}
}).start();
}
}
});
/*
* jsl.addMouseListener(new MouseListener() {
*
* @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated
* method stub nowplaytime=jsl.getValue(); try { player.close(); player=new
* Player(new FileInputStream(playpath)); player.play((int)nowplaytime); } catch
* (JavaLayerException | FileNotFoundException e1) { // TODO Auto-generated
* catch block e1.printStackTrace(); } jslset=false; }
*
* @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated
* method stub jslset=true; }
*
* @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated
* method stub
*
* }
*
* @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated
* method stub
*
* }
*
* @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated
* method stub
*
* } });
*/
JTextField jt1 = new JTextField();
down.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
// down.setEnabled(false);
int h = jl.getSelectedIndex();
if (h == -1) {
if (playmusic) {
playmusic = false;
if (playing) {
down.setText("播放");
player.close();
player = null;
timer.cancel();
task.cancel();
timer = null;
task = null;
}
}
ja.setText("警告:沒有選中執(zhí)行的目標!");
return;
}
PT ts = t.get(h);
if (playing) {
if (playmusic) {
down.setText("播放");
playmusic = false;
player.close();
player = null;
timer.cancel();
task.cancel();
timer = null;
task = null;
} else {
playmusic = true;
changefile cf = new changefile(t, ts, ja, showtime, jsl, down, dlm, h);
new Thread(cf).start();
}
} else {
ja.setText("正在下載:" + ts.title);
ts.title = ts.title.replace("\\", " ");
ts.title = ts.title.replace("/", " ");
new Thread(new Runnable() {
@Override
public void run() {
String filepath = jt1.getText();
File file = new File(filepath);
if (!file.exists()) {
file = null;
ja.setText("警告:保存路徑不可訪問!");
return;
}
file = null;
if (!filepath.equals(savepath)) {
savepath = filepath;
try {
FileOutputStream fo = new FileOutputStream(fp);
fo.write(savepath.getBytes());
fo.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
filepath += "/" + ts.title + ".m4a";
WebGet.you_get(ts.url, filepath);
ja.setText("已保存:" + filepath);
// down.setEnabled(true);
}
}).start();
}
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
});
jf.add(down);
jt1.setBounds(10, 470, 500, 30);
jt1.setText(savepath);
jf.add(jt1);
jsl.setBounds(95, 510, 400, 20);
jsl.setMinimum(0);
jsl.setMaximum(100);
jsl.setValue(0);
jf.add(jsl);
showtime.setBounds(480, 503, 100, 30);
jf.add(showtime);
ja.setBounds(120, 510, 400, 60);
jf.add(ja);
JButton exp = new JButton();
exp.setBounds(520, 470, 30, 30);
exp.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
try {
File f = new File(savepath);
if (!f.exists()) {
f = null;
return;
}
Desktop.getDesktop().open(f);
f = null;
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
});
exp.setIcon(new ImageIcon(MyMain.class.getResource("file.jpg")));
jf.add(exp);
JButton pos = new JButton();
pos.setBounds(560, 470, 30, 30);
pos.setIcon(new ImageIcon(MyMain.class.getResource("music.jpg")));
pos.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if (!playing) {
down.setText("播放");
playing = true;
}
File f = new File(savepath);
if (!f.exists()) {
f = null;
return;
}
dlm.clear();
t.clear();
for (String i : f.list()) {
if(ismusic(i))
{
t.add(new PT(i, savepath + "/" + i));
dlm.addElement(i);
}
}
f = null;
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
});
jf.add(pos);
jf.repaint();
jt.repaint();
// jl.repaint();
jt.requestFocus();
// jf.repaint();
}
public static class changefile implements Runnable {
List<PT> t;
PT ts;
JLabel ja, showtime;
JSlider jsl;
JButton down;
DefaultListModel<String> dlm;
int sel;
public changefile(List<PT> t, PT ts, JLabel ja, JLabel showtime, JSlider jsl, JButton down,
DefaultListModel<String> dlm, int sel) {
// TODO Auto-generated constructor stub
this.t = t;
this.ts = ts;
this.ja = ja;
this.down = down;
this.dlm = dlm;
this.sel = sel;
this.showtime = showtime;
this.jsl = jsl;
}
@Override
public void run() {
// TODO Auto-generated method stub
if (timer != null) {
timer.cancel();
task.cancel();
timer = null;
task = null;
}
if (player != null) {
if (!player.isComplete()) {
if (openmusicfile != null) {
try {
openmusicfile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
openmusicfile = null;
}
player.close();
}
player = null;
if (openmusicfile != null) {
try {
openmusicfile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
openmusicfile = null;
}
}
musictime = getmusictime(ts.url) / 1000;
try {
boolean zh = changeLocalSourceToMp3(ts.url, down, ja);
if (zh) {
for (int i = ts.url.length() - 1; i >= 0; i--) {
if (ts.url.charAt(i) == '.') {
ts.url = ts.url.substring(0, i);
ts.url += ".mp3";
break;
}
}
for (int i = ts.title.length() - 1; i >= 0; i--) {
if (ts.title.charAt(i) == '.') {
ts.title = ts.title.substring(0, i);
ts.title += ".mp3";
t.set(sel, ts);
dlm.set(sel, ts.title);
break;
}
}
down.setEnabled(true);
}
playpath = ts.url;
openmusicfile = new FileInputStream(ts.url);
jsl.setMaximum((int) musictime);
showtime.setText(String.format("00:00/%02d:%02d", musictime / 60, (musictime % 60)));
ja.setText("此音頻時長為:" + musictime / 60 + "分" + (musictime % 60) + "秒!");
timer = new Timer(false);
task = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
nowplaytime++;
if (nowplaytime >= musictime) {
down.setText("播放");
playmusic = false;
nowplaytime = 0;
jsl.setValue(0);
showtime.setText(String.format("00:00/%02d:%02d", musictime / 60, (musictime % 60)));
timer.cancel();
task.cancel();
return;
}
if (!jslset)
jsl.setValue((int) (nowplaytime));
showtime.setText(String.format("%02d:%02d/%02d:%02d", nowplaytime / 60, (nowplaytime % 60),
musictime / 60, (musictime % 60)));
}
};
nowplaytime = 0;
jsl.setValue((int) (nowplaytime));
timer.schedule(task, 1000, 1000);
player = new Player(openmusicfile);
down.setText("停止");
player.play();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
down.setEnabled(true);
}
}
public static long getmusictime(String path) {
File source = new File(path);
if (!source.exists()) {
source = null;
return 0;
}
Encoder encoder = new Encoder();
long ls = 0;
try {
MultimediaInfo m = encoder.getInfo(source);
ls = m.getDuration();
// System.out.println();
} catch (InputFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EncoderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ls;
}
public static boolean changeLocalSourceToMp3(String localFilePath, JButton down, JLabel debug) throws Exception {
if (localFilePath.indexOf(".mp3", localFilePath.length() - 5) != -1)
return false;
down.setEnabled(false);
debug.setText("正在轉(zhuǎn)碼:" + localFilePath);
File source = new File(localFilePath);
String targetPath = null;
for (int i = localFilePath.length() - 1; i >= 0; i--) {
if (localFilePath.charAt(i) == '.') {
targetPath = localFilePath.substring(0, i);
targetPath += ".mp3";
break;
}
}
File target = new File(targetPath);
AudioAttributes audio = new AudioAttributes();
Encoder encoder = new Encoder();
audio.setCodec("libmp3lame");
audio.setBitRate(new Integer(128000));// 音頻流的比特率???
audio.setChannels(new Integer(2));// 聲道
audio.setSamplingRate(new Integer(44100));// 音頻流的采樣??
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp3");
attrs.setAudioAttributes(audio);
encoder.encode(source, target, attrs);
source.delete();
debug.setText("音頻已輸出:" + targetPath);
return true;
}
}以上就是基于Java實現(xiàn)音樂播放器的示例代碼的詳細內(nèi)容,更多關(guān)于Java音樂播放器的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Servlet實現(xiàn)統(tǒng)計頁面訪問次數(shù)功能
這篇文章主要介紹了Servlet實現(xiàn)統(tǒng)計頁面訪問次數(shù)功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-04-04
SpringBoot結(jié)合Neo4j自定義cypherSql的方法
這篇文章主要介紹了SpringBoot結(jié)合Neo4j自定義cypherSql,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-11-11
IDEA中JDK是1.8但Java版本只有21和17的解決辦法
JDK 1.8(Java Development Kit 1.8)是Java平臺的一個版本,它包含了用于開發(fā)和運行Java應用程序的工具和庫,下面這篇文章主要給大家介紹了關(guān)于IDEA中JDK是1.8但Java版本只有21和17的解決辦法,需要的朋友可以參考下2024-01-01
Kafka中的producer攔截器與consumer攔截器詳解
這篇文章主要介紹了Kafka中的producer攔截器與consumer攔截器詳解,Producer 的Interceptor使得用戶在消息發(fā)送前以及Producer回調(diào)邏輯前有機會對消息做 一些定制化需求,比如修改消息等,需要的朋友可以參考下2023-12-12
java實現(xiàn)隨機森林RandomForest的示例代碼
本篇文章主要介紹了java實現(xiàn)隨機森林RandomForest的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08

