java简单播放器源码
- 格式:doc
- 大小:43.50 KB
- 文档页数:7
import java.awt.*;import java.io.*;import java.util.*;import javax.media.*;import javax.media.format.*;import javax.swing.*;public class VideoPlayer implements ControllerListener {Vector audioCapDevList = null;Vector videoCapDevList = null;CaptureDeviceInfo audioCapDevInfo = null;CaptureDeviceInfo videoCapDevInfo = null;MediaLocator audioCapDevLoc = null;MediaLocator videoCapDevLoc = null;Player audioPlayer;Player videoPlayer;public void initAudioCapDevLoc() {//这里可以填写其它的音频编码格式,具体请看AudioFormat类audioCapDevList = CaptureDeviceManager.getDeviceList(new AudioFormat(AudioFormat.LINEAR));if ((audioCapDevList.size() > 0)) {//或许有几个CaptureDevice,这里取第一个audioCapDevInfo = (CaptureDeviceInfo) audioCapDevList.elementAt(0);audioCapDevLoc = audioCapDevInfo.getLocator();} else {System.out.println("找不到音频采集设备");System.exit(0);}}public void initVideoCapDevLoc() {//这里可以填写其它的编码视频格式,具体请看VideoFormat类videoCapDevList = CaptureDeviceManager.getDeviceList(new VideoFormat(VideoFormat.YUV));if ((videoCapDevList.size() > 0)) {//或许有几个CaptureDevice,这里取第一个videoCapDevInfo = (CaptureDeviceInfo)videoCapDevList.elementAt(0);videoCapDevLoc = videoCapDevInfo.getLocator();} else {System.out.println("找不到视频采集设备");System.exit(0);}}public void initAudioPlayer() {try {audioPlayer = Manager.createPlayer(audioCapDevLoc);} catch (NoPlayerException ex) {} catch (IOException ex) {}//增加一个侦听器,侦听player状态的改变audioPlayer.addControllerListener(this);audioPlayer.realize();}public void initVideoPlayer() {try {videoPlayer = Manager.createPlayer(videoCapDevLoc);} catch (NoPlayerException ex) {} catch (IOException ex) {}//增加一个侦听器,侦听player状态的改变videoPlayer.addControllerListener(this);videoPlayer.realize();}public void stopAndClosePlayer(){audioPlayer.stop();audioPlayer.close();videoPlayer.stop();videoPlayer.close();}public synchronized void controllerUpdate(ControllerEvent ce) { Player p = (Player) ce.getSourceController();JFrame jFrame = new JFrame();Component com;if (p == null) {return;}//如果player的状态变为Realizedif (ce instanceof RealizeCompleteEvent) {if ((com = p.getControlPanelComponent()) != null) {jFrame.add(com, BorderLayout.SOUTH);}if ((com = p.getVisualComponent()) != null) {jFrame.add(com, BorderLayout.NORTH);}jFrame.setVisible(true);jFrame.pack();jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); p.start();}}public static void main(String args[]) {V ideoPlayer cap = new VideoPlayer();cap.initAudioCapDevLoc();cap.initVideoCapDevLoc();cap.initAudioPlayer();cap.initVideoPlayer();try {Thread.currentThread().sleep(20000);//20秒后停止并关闭播放器 } catch (InterruptedException ex) {}cap.stopAndClosePlayer();}}。
播放器代码1.代码:<P align=center><TABLE style="BORDER-RIGHT: #ff69b4 3px dashed; BORDER-TOP: #ff69b4 3px dashed; BORDER-LEFT: #ff69b4 3px dashed; BORDER-BOTTOM: #ff69b4 3px dashed" cellSpacing=0 cellPadding=0 bgColor= #ff69b4 ><TBODY><TR><TD><TABLE borderColor= #ff69b4 align=center border=1><TBODY><TR><TD><P align=center><EMBED style="DISPLAY: block; FILTER: Xray; TEXT-ALIGN: center" src=歌曲地址width=300 height=45 type=audio/mpeg loop="- 1" autostart="false" volume="0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>2.代码:<TABLE borderColor=#4f3256 align=center background=/20057/kaka967.20050722115212.png border=1><TBODY><TR><TD style="FILTER: alpha (opacity=50,style=3)"><P align=center> <EMBED src=歌曲地址width=300 height=45 type=audio/mpeg loop="-1" autostart="false" volume="0"></P></TD></TR></TBODY></TABLE>3.代码:<TABLE borderColor=#dee4fe cellSpacing=3 cellPadding=0 background=/UploadFile/2004-12/2004123023101352.gif border=2><TBODY><TR><TD><TABLE align=center border=0><TBODY><TR><TD style="FILTER: alpha (opacity=60,style=3)"><P align=center><EMBED style="FILTER: Gray" src=歌曲地址width=300 height=45 type=audio/mpeg volume="0" autostart="false" loop="-1"> </P></TD></TR></TBODY></TABLE></TD></TR></TBODY> </TABLE>4.代码;<div align="center"><embed style="FILTER: wave(add=0,lightstrength=50,strength=4,freq=2,phrase=30); WIDTH: 350px; HEIGHT: 50px" src="音乐地址" width="128" height="128" type="audio/mpeg" volume="0" loop="false" autostart="false" showstatusbar="1" /></div>5.代码:<div align="center"><embed style="FILTER: Xray(); WIDTH: 350px; HEIGHT: 50px" src="音乐地址" width="128" height="128" type="audio/mpeg" volume="0" loop="false" autostart="false" showstatusbar="1" /></div>6.代码:<div align="center"><embed style="FILTER: invert(); WIDTH: 350px; HEIGHT: 50px" src="音乐地址" type="audio/mpeg" loop="false" autostart="false" showstatusbar="1" /></div>7.代码:<div align="center"><embed style="FILTER: alpha(opacity=100,style=3); WIDTH: 350px; HEIGHT: 50px" src="音乐地址" width="128" height="128" type="audio/mpeg" volume="0" loop="false" autostart="false" showstatusbar="1" /></div>8.代码:<CENTER><TABLE style="BORDER-TOP-STYLE: dotted; BORDER-RIGHT-STYLE: dotted; BORDER-LEFT-STYLE: dotted; BORDER-BOTTOM-STYLE: dotted" borderColor=#006400 height=45 cellSpacing=0 cellPadding=0 width=400 background=/UploadFile/2005-9/200597123237734.gif border=5><TBODY><TR><TD><TABLE align=center border=0><TBODY><TR><TD style="FILTER: alpha(opacity=60,style=3)"><P align=center><EMBED style="FILTER: Gray" src=音乐地址width=400 height=45 type=audio/mpeg loop="-1" autostart="true" volume="0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></CENTER>9.代码:<P align=center><TABLE style="FILTER: Alpha(Opacity=100, FinishOpacity=0, Style=2, StartX=20, StartY=40, FinishX=0, FinishY=0)gray(); WIDTH: 259px; HEIGHT: 83px"><TBODY><TR><TD><EMBED src=音乐地址width=250 height=40 type=audio/mpeg loop="true" autostart="true" panel="0"></TD></TR></TBODY></TABLE></P>10.代码:<TABLE borderColor=#000000 height=49 cellSpacing=0 cellPadding=0 width=324align=leftbackground=/UploadFile/2005-12/2005121520294992.gifborder=0><TBODY><TR><TD width=324 height=60 cellSpacing="0" cellPadding="0"></TD></TR><TR><TD align=left><P align=center><EMBED src=音乐地址width=300 height=24type=application/x-mplayer2 loop="-1" autostart="1" volume="0"> </P><P align=center> </P></TD></TR></TBODY></TABLE></P>11.代码:<TABLE style="BORDER-RIGHT: #008b8b 3px dashed; BORDER-TOP: #008b8b 3pxdashed; BORDER-LEFT: #008b8b 3px dashed; BORDER-BOTTOM: #008b8b 3px dashed" cellSpacing=0 cellPadding=0 bgColor=white><TBODY><TR><TD><TABLE borderColor=#5f9ea0 align=center bgColor=#5f9ea0 border=2><TBODY><TR><TD style="FILTER: alpha(opacity=100,style=3)"><P align=center><EMBED src=音乐地址width=300 height=45 type=audio/mpeg loop="-1" autostart="false" volume="0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE> 家代码:<table style="filter: alpha(opacity=100 Style=0 FinishOpacity=100); font-size: 16px; color: #000000" borderColor="#000000" height="249" cellSpacing="0" cellPadding="0" width="316" align="center" background="/web_file/blog/167/9167/1/rosa-77-06-2.gif" border="0" id="table1"><tr><td width="314" height="180" cellpadding="0" cellspacing="0"></td></tr><tr><td align="left"><p align="center"><embed style="FILTER: alpha(opacity=100 Style=3 FinishOpacity=0)black(); style: " src="歌曲地址" width="310" height="28" type="video/x-ms-asf" volume="0" autostart="1" loop="-1"></td></tr></table>注:width=播放器的宽度;height=播放器的高度;还介绍两个参数,可以根据自己的需要可以使用它们。
java⾳乐播放器实现代码本⽂实例为⼤家分享了java⾳乐播放器的具体代码,供⼤家参考,具体内容如下这个是源码结构介绍这个是界⾯,有点简陋,见笑了,但是基本上的东西都有了,没办法,没有美⼯的程序写的界⾯直接上源代码Player.javapackage com.service;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.Random;import javax.sound.sampled.*;import javax.swing.JSlider;import javax.swing.JTable;import com.list.MusicList;import com.list.ThreadList;import com.list.ViewList;import com.model.Model;import com.model.Music;import com.view.View;/*"duration""author""title""copyright"private Player p;private long time = 0;Object lock = new Object();//⼀个空的对象,没什么意义private boolean paused = false;// 暂停继续public boolean isPaused() {return paused;}public void setPaused(boolean paused) {this.paused = paused;}private JSlider jSliderPlayProgress;//播放进度条private boolean over = false;//开始结束//是否⾃动播放下⼀曲private boolean isNext=true;private Music music;//⾳乐AudioInputStream din = null;SourceDataLine line=null;private FloatControl volume = null;private JSlider jSliderVolume;public JSlider getjSliderVolume() {return jSliderVolume;}public void setjSliderVolume(JSlider jSliderVolume) {this.jSliderVolume = jSliderVolume;}public Player(JSlider jSliderVolume,JSlider jSliderPlayProgress) { super();this.jSliderVolume = jSliderVolume;this.jSliderPlayProgress=jSliderPlayProgress;}public Music getMusic() {return music;}public void setMusic(Music music) {this.music = music;}public FloatControl getVolume(){return volume;}//播放⾳乐public void run(){AudioInputStream in=null;try {File file = new File(music.getPath());//播放不了的歌曲,直接下⼀⾸,并且在⾳乐列表中删除try {ViewList.getList().get(0).getJt().setModel(new Model());nextmusic();}AudioFormat baseFormat = in.getFormat();AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,baseFormat.getSampleRate(), 16, baseFormat.getChannels(),baseFormat.getChannels() * 2, baseFormat.getSampleRate(),false);if(baseFormat.getEncoding()==AudioFormat.Encoding.PCM_UNSIGNED || baseFormat.getEncoding()==AudioFormat.Encoding.ULAW || baseFormat.getEncoding()==AudioFormat.Encoding.ALAW || baseFormat.getEncoding()==AudioFormat.Encoding.PCM_SIGNED){time=(file.length()*8000000)/((int)(decodedFormat.getSampleRate()*baseFormat.getSampleSizeInBits()));}else{int bitrate=0;if(baseFormat.properties().get("bitrate")!=null){//取得播放速度(单位位每秒)bitrate=(int)((Integer)(baseFormat.properties().get("bitrate")));if(bitrate!=0)time=(file.length()*8000000)/bitrate;}}din = AudioSystem.getAudioInputStream(decodedFormat, in); info = new (SourceDataLine.class, decodedFormat);line = (SourceDataLine) AudioSystem.getLine(info);line.open();setVolume();jSliderPlayProgress.setMaximum((int)time);jSliderPlayProgress.setValue(0);if(line!=null){line.open(decodedFormat);byte[] data = new byte[4096];int nBytesRead;synchronized (lock) {while ((nBytesRead = din.read(data, 0, data.length)) != -1) {while (paused) {if(line.isRunning()) {line.stop();System.out.println("暂停");}try {lock.wait();System.out.println("等待");}catch(InterruptedException e) {}}if(!line.isRunning()&&!over) {System.out.println("开始播放");line.start();}if (over&&line.isRunning()) {System.out.println("停⽌播放");jSliderPlayProgress.setValue(0);isNext=false;line.drain();line.stop();line.close();}jSliderPlayProgress.setValue((int)line.getMicrosecondPosition());line.write(data, 0, nBytesRead);}//根据播放模式选择下⼀⾸歌nextmusic();}}finally {if(din != null) {try { din.close(); } catch(IOException e) { }}}}//设置播放器滚动条public void setVolume(){if(line!=null){if(line.isControlSupported(FloatControl.Type.MASTER_GAIN)){jSliderVolume.setEnabled(true);volume= (FloatControl)line.getControl( FloatControl.Type.MASTER_GAIN );jSliderVolume.setMinimum((int)volume.getMinimum());jSliderVolume.setMaximum((int)volume.getMaximum());//jSliderVolume.setValue((int)(volume.getMinimum()+(4*(volume.getMaximum()-volume.getMinimum()))/5)); volume.setValue((float)(volume.getMinimum()+(4*(volume.getMaximum()-volume.getMinimum()))/5));}}else{volume=null;jSliderVolume.setEnabled(false);}}private void nextmusic() {String mode=Setting.getMode();if (isNext&&!mode.equals("one")) {//单曲播放就不执⾏int nextid=0;//将要播放的idint currentid=Integer.parseInt(this.music.getId());System.out.println(mode);if (mode.equals("default")&&(currentid==MusicList.getList().size()-1)){return;}if (mode.equals("rand")) {Random random = new Random();nextid=Math.abs(random.nextInt())%MusicList.getList().size();}else if (mode.equals("onecircle")) {nextid=currentid;}else if (mode.equals("default")&&!(currentid==MusicList.getList().size()-1)) {nextid=currentid+1;}else if (mode.equals("morecircle")) {nextid=(currentid==MusicList.getList().size()-1)?0:currentid+1;}JTable jTable=ViewList.getList().get(0).getJt();if(nextid==0){//第⼀个jTable.setRowSelectionInterval(0,0);}else {jTable.setRowSelectionInterval(nextid-1,nextid);}this.stopplay();ThreadList.getList().clear();p=new Player(jSliderVolume,jSliderPlayProgress);p.setMusic(MusicList.getList().get(nextid));ThreadList.getList().add(p);p.start();}}//开始public void startplay(){over=false;}//停⽌public void stopplay(){// 暂停public void userPressedPause() {paused = true;}//继续public void userPressedPlay() {synchronized(lock) {paused = false;lock.notifyAll();}}public void Pause(){if (paused) {synchronized(lock) {paused = false;lock.notifyAll();}}else{paused = true;}}}这个主要是播放⾳乐的类,播放,暂停,停⽌,上⼀⾸,下⼀⾸都有了 View.javapackage com.view;import java.awt.BorderLayout;import java.awt.Color;import ponent;import java.awt.Container;import java.awt.Dimension;import java.awt.GridLayout;import java.awt.Image;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import java.io.File;import java.io.IOException;import .URI;import .URL;import java.util.ArrayList;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JComponent;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JRootPane;import javax.swing.JScrollPane;import javax.swing.JSlider;import javax.swing.JTable;import javax.swing.ListSelectionModel;import javax.swing.ScrollPaneConstants;import javax.swing.SwingConstants;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;import javax.swing.table.TableCellRenderer;import com.list.ViewList;import com.model.Model;import com.model.Music;import com.service.Player;import com.service.Setting;import com.util.DirInput;import com.util.FileInput;import com.util.FileList;import com.util.List_File;public class View extends JFrame implements MouseListener,ActionListener,WindowListener { private JButton stop, open,del,next,pre;private Player p;private JPanel[] jPanels;private MusicList list;//private Long clickTime=0l;private JScrollPane jsp;private JTable jt;private JRootPane j;private Model model;private JSlider jSliderVolume;private JSlider jSliderPlayProgress;private FileInput fileinput;private DirInput dirInput;private JMenuBar jb;private JMenu jm;private JMenuItem fm,dm;private JComboBox jBox;public View(){System.out.println(ViewList.getList().size());if (ViewList.getList().size()==0) {Open();}}private void Open() {//this.getRootPane().setWindowDecorationStyle(JRootPane.NONE);//this.setUndecorated(true);//菜单选项jb=new JMenuBar();jm=new JMenu("打开");fm=new JMenuItem("⽂件");dm=new JMenuItem("⽂件夹");fm.addActionListener(this);dm.addActionListener(this);jb.add(jm);jm.add(fm);jm.add(dm);//this.setJMenuBar(jb);JPanel p1=new JPanel();JPanel p2=new JPanel();JPanel p3=new JPanel();//增加菜单选项j=new JRootPane();j.setJMenuBar(jb);open=new JButton("播放");stop=new JButton("停⽌");open.addMouseListener(this);stop.addMouseListener(this);pre=new JButton("上⼀⾸");next=new JButton("下⼀⾸");pre.addMouseListener(this);next.addMouseListener(this);p1.setLayout(new GridLayout(2,1));JPanel jPanel2=new JPanel();jPanel2.add(open);jPanel2.add(stop);jPanel2.add(pre);jPanel2.add(next);p1.add(jPanel2);/*p1.add(open);p1.add(stop);p1.add(pre);p1.add(next);*/del=new JButton("删除");del.addMouseListener(this);jSliderPlayProgress = new JSlider(); //播放进度条jSliderPlayProgress.setValue(0);jSliderPlayProgress.setEnabled(false);jSliderPlayProgress.setPreferredSize(new Dimension(200, 20));p1.add(jSliderPlayProgress);jSliderVolume = new JSlider(); //⾳量进度条jSliderVolume.setValue(0);//jSliderPlayProgress.setEnabled(false);jSliderVolume.setPreferredSize(new Dimension(100, 20));//设置滚动条长度jSliderVolume.addChangeListener(new ChangeListener(){public void stateChanged(ChangeEvent evt){System.out.println(jSliderVolume.getValue());if (ThreadList.getList().size()!=0) {ThreadList.getList().get(0).getVolume().setValue((float)jSliderVolume.getValue()); }}});String[] v={"顺序播放","随机播放","单曲循环","列表循环","单曲播放"};jBox=new JComboBox(v);jBox.addActionListener(this);p2.add(jBox);p2.add(del);p2.add(jSliderVolume);jPanels=new JPanel[list.getList().size()];for (int i = 0; i < list.getList().size(); i++) {Music music=list.getList().get(i);JPanel jPanel=new MyJPanel(music);JLabel jLabel=new JLabel(music.getName(),SwingConstants.CENTER);jLabel.setSize(300, 10);jPanels[i]=jPanel;jPanel.addMouseListener(this);jPanel.add(jLabel);p3.add(jPanel);}p3.setBackground(Color.WHITE);p3.setLayout(new GridLayout(10, 1));p3.setSize(320, 500);this.add(p1,BorderLayout.NORTH);this.add(p2,BorderLayout.SOUTH);model=new Model(); //添加表jt=new JTable(model){ // 设置jtable的单元格为透明的public Component prepareRenderer(TableCellRenderer renderer,int row, int column) {Component c = super.prepareRenderer(renderer, row, column);if (c instanceof JComponent) {((JComponent) c).setOpaque(false);}return c;}};;jt.setOpaque(false);jt.setRowHeight(30);jt.setSelectionMode(ListSelectionModel.SINGLE_SELECTION );jt.setShowHorizontalLines(false);jt.setSelectionBackground(new Color(189,215,238));jt.addMouseListener(this);jsp = new JScrollPane(jt);jsp.setOpaque(false);jsp.getViewport().setOpaque(false);//addmusic();//this.add(p3,BorderLayout.CENTER);this.add(jsp,BorderLayout.CENTER);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.addWindowListener(this);Image image=this.getToolkit().getImage("img/icon.jpg");this.setIconImage(image);this.setTitle("⾳乐播放器");ImageIcon icon = new ImageIcon("img/bg.jpg");JLabel lab = new JLabel(icon); // 将图⽚放⼊到label中lab.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight()); // 设置放有图⽚的label的位置this.getContentPane().add(lab, -1); // jthis本⾝是窗体,不能放置任何组件,⽤getContentPane()⽅法得到this的默认内容⾯板,将lab放⼊其中,-1表⽰放⼊⾯板的下层jSliderVolume.setOpaque(false);jPanel2.setOpaque(false);p1.setOpaque(false);p3.setOpaque(false);jSliderPlayProgress.setOpaque(false);this.setLocation(400, 200);this.setSize(337, 525);this.setResizable(false);this.setVisible(true);}@Overridepublic void mouseClicked(MouseEvent e) {System.out.println("开始播放");if (e.getSource()==open) {if (p==null) {//开始p=new Player(jSliderVolume,jSliderPlayProgress);p.setMusic(MusicList.getList().get(0));jt.setRowSelectionInterval(0,0);ThreadList.add(p);open.setText("暂停");p.start();}else{//继续if (ThreadList.getList().size()!=0) {p=ThreadList.getList().get(0);}String s=p.isPaused()?"暂停":"播放";open.setText(s);p.Pause();}}else if (e.getSource()==stop) {if (ThreadList.getList().size()!=0) {p=ThreadList.getList().get(0);}if (p!=null) {p.stopplay();p=null;open.setText("播放");}}else if (e.getSource()==pre) {//上⼀⾸premusic();}else if (e.getSource()==next) {//下⼀⾸nextmusic();}else if (e.getSource()==del) {delmusic();}else if (e.getSource()==jt&&e.getClickCount()==2) {//双击 clickmusic();}}private void clickmusic() {//双击JtableSystem.out.println("点击了");int rowNum = this.jt.getSelectedRow();System.out.println(rowNum);if(rowNum == -1) {JOptionPane.showMessageDialog(this, "你没有选择⼀项"); return;}ArrayList<Player> list=ThreadList.getList();p=new Player(jSliderVolume,jSliderPlayProgress);p.setMusic(MusicList.getList().get(rowNum));ThreadList.add(p);open.setText("暂停");p.start();}else{System.out.println("停⽌");list.get(0).stopplay();list.clear();p=new Player(jSliderVolume,jSliderPlayProgress);p.setMusic(MusicList.getList().get(rowNum));open.setText("暂停");list.add(p);p.start();}}private void delmusic() {int rowNum = this.jt.getSelectedRow();MusicList.getList().remove(rowNum);System.out.println(MusicList.getList().size());jt.setModel(new Model());ArrayList<Player> list=ThreadList.getList();p=new Player(jSliderVolume,jSliderPlayProgress);System.out.println(list.size()+"⼤⼩");if (list.size()!=0) {list.get(0).stopplay();list.clear();open.setText("暂停");if(rowNum==0){//第⼀个System.out.println("第⼀个");jt.setRowSelectionInterval(0,0);p.setMusic(MusicList.getList().get(rowNum));}else if(rowNum==MusicList.getList().size()){//最后⼀个 System.out.println("最后⼀个");jt.setRowSelectionInterval(rowNum-2,rowNum-1);p.setMusic(MusicList.getList().get(rowNum-1));}else {System.out.println("中间");jt.setRowSelectionInterval(rowNum-1,rowNum);p.setMusic(MusicList.getList().get(rowNum));}list.add(p);p.start();}}public JTable getJt() {return jt;}private void premusic() {System.out.println("上⼀⾸");ArrayList<Player> list=ThreadList.getList();int id=Integer.parseInt(list.get(0).getMusic().getId());if(id!=0){if (id==1) {jt.setRowSelectionInterval(0,0);}else{jt.setRowSelectionInterval(id-2,id-1);}System.out.println(id);p=new Player(jSliderVolume,jSliderPlayProgress); p.setMusic(MusicList.getList().get(id-1));System.out.println(id-1);open.setText("暂停");list.add(p);p.start();}}private void nextmusic() {System.out.println("下⼀⾸");ArrayList<Player> list=ThreadList.getList();int id=Integer.parseInt(list.get(0).getMusic().getId()); System.out.println(id);if(id!=MusicList.getList().size()-1){ //122jt.setRowSelectionInterval(id,id+1); //123条list.get(0).stopplay();list.clear();p=new Player(jSliderVolume,jSliderPlayProgress); p.setMusic(MusicList.getList().get(id+1));System.out.println(id+1);open.setText("暂停");list.add(p);p.start();}}//判断双击/* private boolean checkClickTime() {long nowTime = (new Date()).getTime();if ((nowTime - clickTime) < 300) {clickTime = nowTime;return true;}clickTime = nowTime;return false;}*/private void addmusic(String path) {//增加mp3⽂件夹 System.out.println("增加mp3⽂件夹");ArrayList<Music> musiclist=MusicList.getList();List_File fm = new List_File();ArrayList<String[]> FileList = fm.serachFiles(path); for (int i = 0; i < FileList.size(); i++) {Music music= new Music();music.setId(musiclist.size()+"");String[] s=(String[]) FileList.get(i);music.setName(s[0]);music.setPath(s[1]);musiclist.add(music);}jt.setModel(new Model());}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void actionPerformed(ActionEvent e) {if (e.getSource()==fm) {//添加mp3⽂件if(fileinput==null) fileinput = new FileInput(this);fileinput.open();File[] s=fileinput.getFiles();ArrayList<Music> musiclist=MusicList.getList();if(s!=null){for(int i=0;i<s.length;i++){Music music= new Music();music.setId(musiclist.size()+"");music.setName(s[i].getName());music.setPath(s[i].getAbsolutePath());musiclist.add(music);jt.setModel(new Model());}}}else if (e.getSource()==dm) {if(dirInput==null) dirInput = new DirInput(this);dirInput.open();File s=dirInput.getFile();if(s!=null){addmusic(s.getAbsolutePath());}}else if (e.getSource()==jBox) {//顺序播放 (默认)default 随机rand 单曲循环 onecircle 列表循环 morecircle 单曲播放 one if (ThreadList.getList().size()!=0) {p=ThreadList.getList().get(0);}else {p=new Player(jSliderVolume,jSliderPlayProgress);ThreadList.getList().add(p);}String[] s={"default","rand","onecircle","morecircle","one"};Setting.setMode(s[jBox.getSelectedIndex()]);}}@Overridepublic void windowActivated(WindowEvent e) {// TODO Auto-generated method stub}@Overridepublic void windowClosed(WindowEvent e) {// TODO Auto-generated method stubSystem.out.println("关闭kk");}@Overridepublic void windowClosing(WindowEvent e) {// TODO Auto-generated method stubSystem.out.println("close");if (MusicList.getList().size()!=0) {System.out.println("写⼊⽂件");//清空之前的内容FileList.clear("file/musiclist.txt");ArrayList<Music> list=MusicList.getList();for (int i = 0; i < list.size(); i++) {FileList.writeFile("file/musiclist.txt",list.get(i).getId()+","+list.get(i).getName()+","+list.get(i).getPath()+"\n");}}}@Overridepublic void windowDeactivated(WindowEvent e) {// TODO Auto-generated method stub}@Overridepublic void windowDeiconified(WindowEvent e) {// TODO Auto-generated method stub}@Overridepublic void windowIconified(WindowEvent e) {// TODO Auto-generated method stub}@Overridepublic void windowOpened(WindowEvent e) {// TODO Auto-generated method stubSystem.out.println("open");File file=new File("file/musiclist.txt");if (file.exists()==false) {try {file.createNewFile();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}else {FileList.readFileByLines("file/musiclist.txt");jt.setModel(new Model());}}}剩下的代码在后⾯附件上有,现在主要是有⼏个⼩问题,第⼀,我还没有找到获取⾳乐⽂件具体信息⽐较好的办法,所以每⼀⾸暂时还没有歌⼿,作曲的信息,第⼆界⾯有点难看,见谅了,第三个是打包成jar⽂件会有路径问题,暂时还没办法解决,我是直接在myeclipse上运⾏,⼀切正常,就是打包有点⼩问题暂时先说这些了,这个是我业余时间的项⽬,有什么不⾜的,⼤家都可以提出来。
//程序所用到的各种程序包import java.awt.BorderLayout;import java.awt.CheckboxMenuItem;import java.awt.Color;import ponent;import java.awt.Container;import java.awt.FileDialog;import java.awt.Font;import java.awt.FontMetrics;import java.awt.Graphics;import java.awt.Menu;import java.awt.MenuBar;import java.awt.MenuItem;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.media.ControllerClosedEvent;import javax.media.ControllerEvent;import javax.media.ControllerListener;import javax.media.EndOfMediaEvent;import javax.media.GainControl;import javax.media.Manager;import javax.media.MediaLocator;import javax.media.NoPlayerException;import javax.media.Player;import javax.media.PrefetchCompleteEvent;import javax.media.RealizeCompleteEvent;import javax.media.Time;import javax.swing.JFrame;//本程序对应的类;class MediaPlayerextends JFrameimplements ActionListener, ControllerListener, ItemListener {//MediaPlayer类的变量成员的声明;//JMF提供的播放器对象;Player player;Component vc, cc, gcc;GainControl gc;//first值用来控制在刚开始程序时显示一幅欢迎界面;loop用以标记是否循环播放;boolean first = true, loop = false;//设立一个字符串记录当前打开文件的路径String currentDirectory;MediaPlayer(String title) {super(title);// 利用一个adapter实现对用户点击窗口系统菜单的关闭按钮// 时的响应;addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {//调用dispose以执行windowCloseddispose();}public void windowClosed(WindowEvent e) {if (player != null)player.close();System.exit(0);}});//调用设置程序菜单栏的方法成员完成菜单的布置setupMenu();setSize(400, 400);setVisible(true);}//本方法用以设置程序菜单栏public void setupMenu() {//设置一个菜单Menu f = new Menu("文件");//往设置的菜单种添加菜单项MenuItem mi = new MenuItem("打开");mi.addActionListener(this);f.add(mi);f.addSeparator();CheckboxMenuItem cbmi = new CheckboxMenuItem("循环", false);cbmi.addItemListener(this);f.add(cbmi);f.addSeparator();mi = new MenuItem("退出");mi.addActionListener(this);f.add(mi);Menu l = new Menu("播放列表");Menu c = new Menu("播放控制");MenuItem move = new MenuItem("播放");move.addActionListener(this);c.add(move);c.addSeparator();MenuItem pause = new MenuItem("暂停");pause.addActionListener(this);c.add(pause);c.addSeparator();MenuItem stop = new MenuItem("停止");stop.addActionListener(this);c.add(stop);c.addSeparator();//设置一个菜单栏MenuBar mb = new MenuBar();//将设置的菜单依次加入程序的菜单栏中去mb.add(f);mb.add(c);mb.add(l);//将构造完成的菜单栏交给当前程序的窗口;setMenuBar(mb);}//事件响应成员;捕捉发送到本对象的各种事件;public void actionPerformed(ActionEvent e) {//设一个字符串用于暂存打开的媒体文件的路径;String cufile , selcectfile;if (e.getActionCommand().equals("退出")) {// 调用dispose以便执行windowCloseddispose();return;}//次事件表明用户选择了"播放"菜单命令;//如果当前有一个文件可以播放则执行播放命令;if (e.getActionCommand().equals("播放")) {if (player != null) {player.start();}return;}//如果当前正在播放某一文件,则执行暂停;if (e.getActionCommand().equals("暂停")) {if (player != null) {player.stop();}return;}//次事件表明用户选择了"播放"菜单命令;//如果当前有一个文件可以播放则执行播放命令;if (e.getActionCommand().equals("停止")) {if (player != null) {player.stop();player.setMediaTime(new Time(0));}return;}//用户选择要播放的媒体文件if (e.getActionCommand().equals("打开")) {FileDialog fd = new FileDialog(this, "打开媒体文件", FileDialog.LOAD);fd.setDirectory(currentDirectory);fd.show();// 如果用户放弃选择文件,则返回if (fd.getFile() == null)return;//保存了所选文件的名称及其全路径名称已被稍后使用//同时设置当前文件夹路径selcectfile = fd.getFile();currentDirectory = fd.getDirectory();cufile = currentDirectory + selcectfile;//将用户选择的文件作为一个菜单项加入播放列表该菜单项"名为"该文件名;//被点击后给出的命令串是该文件的全路径名MenuItem mi = new MenuItem(selcectfile);mi.setActionCommand(cufile);MenuBar mb = getMenuBar();Menu m = mb.getMenu(2);mi.addActionListener(this);m.add(mi);} else {//程序逻辑运行到此表示用户选择了一个"播放列表"中的媒体文件//此时可以通过如下动作获得该文件的全路径名;cufile = e.getActionCommand();selcectfile = cufile;}//如果已存在一个播放器,则先将其关闭,稍后重新创建//创建播放器时需要捕捉一些异常;if (player != null)player.close();try {player = Manager.createPlayer(new MediaLocator("file:" + cufile));} catch (java.io.IOException e2) {System.out.println(e2);return;} catch (NoPlayerException e2) {System.out.println("不能找到播放器.");return;}if (player == null) {System.out.println("无法创建播放器.");return;}first = false;setTitle(selcectfile);//设置处理播放控制器实际的对象;player.addControllerListener(this);player.prefetch();}//因为实现了"ControllerListener"接口,本方法用于处理媒体播放器传来的事件;public void controllerUpdate(ControllerEvent e) {Container tainer = getContentPane();// 调用player.close()时ControllerClosedEvent事件出现。
JavaFX在一分钟内编写一个视频播放器首先在Netbeans下新建一个JavaFX空项目。
然后从左边拖一个stage进来Stage是一个javaFX的基础,一个Stage下包含一个sence,就是我们放可视的组件的地方。
改一下大小,取个名字如下:1Stage{2title:"mediaplayer"3scene:Scene{4width:4005height:3506content:[78]9}10}接下来我们到底下的Swing组件里头拖进来一个按钮,并取个名字。
放到content中1SwingButton{2text:"Play"3action:function(){45}6}接下来添加播放器的代码。
因为播放器没有在左边列出来,我们需要import,然后手动写代码。
如下1importjavafx.scene.media.Media;2importjavafx.scene.media.MediaPlayer;3importjavafx.scene.media.MediaView;45//media是用来放电影地址的6varmedia=Media{source:"XX"}78//添加播放器9varplayer=MediaPlayer{media:media,autoPlay:false}接下来我们把各个部分组合起来:注意content里头新加的内容。
1importjavafx.stage.Stage;2importjavafx.scene.Scene;3importjavafx.ext.swing.SwingButton;4importjavafx.scene.media.Media;5importjavafx.scene.media.MediaPlayer;6importjavafx.scene.media.MediaView;78varmedia=Media{source:"XX"}9varplayer=MediaPlayer{media:media,autoPlay:false}1011Stage{12title:"mediaplayer"13scene:Scene{14width:40015height:35016content:[17MediaView{18mediaPlayer:player19}20SwingButton{21text:"player"22action:function(){23player.play()24}25}2627]28}29}如果按下运行,窗口还是半天没出来,请自行更换flv的源。
java播放mp3oggapeflac音乐java播放mp3/ogg/ape/flac音乐博客分类:•游戏音乐好吧,又要说一句了,java真是无所不能。
用java sound api播放wav, aiff, au, snd文件想必大家都已经知道了,这些格式是jdk原生支持的。
本文将介绍如何播放mp3/ogg/ape/flac音乐。
其实都是批发来的,我只是搬运工Σ( ° △ °|||)︴1. 先上代码Java代码1.import java.io.File;2.import java.io.IOException;3.4.import javax.sound.sampled.AudioFormat;5.import javax.sound.sampled.AudioInputStream;6.import javax.sound.sampled.AudioSystem;7.import javax.sound.sampled.DataLine;8.import javax.sound.sampled.SourceDataLine;9.10.public class AudioFilePlayer {11.12.public static void main(String[] args) {13.final AudioFilePlayer player = new AudioFilePlayer ();14.player.play("D:/xiaomi.ogg");15.//player.play("D:/01 - 謎解きはディナーのあとで.mp3");16.//player.play("D:/周杰伦-青花瓷.APE");17.//player.play("D:/周杰伦 - 听妈妈的话.flac");18.}19.20.public void play(String filePath) {21.final File file = new File(filePath);22.23.try {24.final AudioInputStream in = AudioSystem.getAudioIn putStream(file);25.26.final AudioFormat outFormat = getOutFormat(in.getF ormat());27.final info = new (SourceDat aLine.class, outFormat);28.29.final SourceDataLine line = (SourceDataLine) AudioSys tem.getLine(info);30.31.if (line != null) {32.line.open(outFormat);33.line.start();34.stream(AudioSystem.getAudioInputStream(outFormat, in), line);35.line.drain();36.line.stop();37.}38.39.} catch (Exception e) {40.throw new IllegalStateException(e);41.}42.}43.44.private AudioFormat getOutFormat(AudioFormat inFo rmat) {45.final int ch = inFormat.getChannels();46.final float rate = inFormat.getSampleRate();47.return new AudioFormat(AudioFormat.Encoding.PCM_ SIGNED, rate, 16, ch, ch * 2, rate, false);48.}49.50.private void stream(AudioInputStream in, SourceDataL ine line)51.throws IOException {52.final byte[] buffer = new byte[65536];53.for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {54.line.write(buffer, 0, n);55.}56.}57.}你没有看错,代码其实很简单,就是普通的java sound api,和原来播放wav, aiff, au, snd没什么两样。
jwplayer=java播放器播放器快速启动向导开始将播放器插入你的网站很简单,只需三步:1,从下载的zip中上传jwplayer.js 和player.swf文件到服务器,下载的其他文件如文档、源代码等可选择性上传。
2,在网页的头部包含jwplayer.js (/网页包含此头文件)<script type="text/javascript" src="/jwplayer/jwplayer.js"></script>(书写体=“文本/Java描述语言”标准要求代码=“java播放器/jwplayer.js”)(/书写)3,在网页的主体部分调用(/调用指定帧)播放器设置,下面是一个基本示例:<div id="container">Loading the player ...</div><script type="text/javascript">jwplayer("container").setup({flashplayer: "/jwplayer/player.swf",file: "/uploads/video.mp4",height: 270,width: 480});</script> (这是一段程序,我就不用再翻了吧)当页面加载时,Java播放器就会在<div>的顶部自动实例化。
默认情况下,播放器就会显示在Flash中。
如果Flash不支持(比如在ipad中),播放器就会在HTML5中显示出来。
播放器的选项(JavaScript中介绍swf的位置)仅是用来配置jw播放器的众多配置选项中的一个。
下面是另一个安装(setup)示例,这次我们用一个<video>标签代替通用的div:<videosrc="/videos/video.mp4"height="270"id="container"poster="/thumbs/image.jpg"width="480"></video><script type="text/javascript">jwplayer("container").setup({flashplayer: "/jwplayer/player.swf"});</script>在这个示例中,jw播放器实际上是用来检测<vedio>标签和加载属性的一个配置选项。
importjavax.media.*;importjava.awt.*;importjava.awt.event.*;classMediaPlayer extends Frame implements ActionListener, ControllerListener, ItemListener{Player player;Component vc, cc;boolean first = true, loop = false;String currentDirectory;MediaPlayer (String title){super (title);addWindowListener(newWindowAdapter (){ public void windowClosing (WindowEvent e){// 用户点击窗口系统菜单的关闭按钮// 调用dispose以执行windowCloseddispose ();}public void windowClosed (WindowEvent e){if (player != null) player.close ();System.exit (0); } });Menu m = new Menu ("文件");MenuItem mi = new MenuItem ("打开");mi.addActionListener (this);m.add (mi);m.addSeparator ();CheckboxMenuItemcbmi = new CheckboxMenuItem ("循环", false); cbmi.addItemListener (this);m.add (cbmi);m.addSeparator ();mi = new MenuItem ("退出");mi.addActionListener (this);m.add (mi);MenuBarmb = new MenuBar ();mb.add (m);setMenuBar (mb);setSize (200, 200);setVisible (true);}public void actionPerformed (ActionEvent e){if (e.getActionCommand ().equals ("退出")){// 调用dispose以便执行windowClosed dispose ();return;}FileDialogfd = new FileDialog (this, "打开媒体文件", FileDialog.LOAD);fd.setDirectory (currentDirectory);fd.show ();// 如果用户放弃选择文件,则返回if (fd.getFile () == null) return;currentDirectory = fd.getDirectory ();if (player != null)player.close ();try{player = Manager.createPlayer (new MediaLocator ("file:" + fd.getDirectory () + fd.getFile ()));}catch (java.io.IOException e2){System.out.println (e2);return;}catch (NoPlayerException e2){System.out.println ("不能找到播放器.");return;}if(player == null){System.out.println ("无法创建播放器.");return;}first = false;setTitle (fd.getFile ());player.addControllerListener (this);player.prefetch ();}public void controllerUpdate (ControllerEvent e){// 调用player.close()时ControllerClosedEvent事件出现。
Java实战音乐播放器-播放音乐文件,包括基本的音频控制创建一个基本的音乐播放器是一个有趣而复杂的项目,它涉及到音频文件的处理、用户界面的设计以及音频控制功能的实现。
在这个实战博客中,我将向您展示如何使用Java来创建一个简单的音乐播放器。
我们将使用Java的Swing库来构建用户界面,以及Java的javax.sound.sampled库来处理音频文件和音频控制。
这个播放器将能够加载和播放本地音频文件,包括基本的音频控制功能,如播放、暂停、停止和音量调节。
步骤1:创建Java项目首先,创建一个新的Java项目,并添加Swing和javax.sound.sampled库的依赖。
您可以使用Eclipse、IntelliJ IDEA或任何其他Java集成开发环境来完成这些任务。
步骤2:创建用户界面在我们的音乐播放器中,我们需要一个用户界面来加载和控制音乐文件。
我们将使用Swing 来创建以下基本组件:文件选择器:用于选择要播放的音乐文件。
播放按钮:用于开始或继续播放音乐。
暂停按钮:用于暂停音乐的播放。
停止按钮:用于停止音乐的播放。
音量控制:用于调整音量。
下面是一个示例的用户界面代码:javaCopy codeimport javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class MusicPlayerGUI extends JFrame {private JButton playButton;private JButton pauseButton;private JButton stopButton;private JSlider volumeSlider;private JFileChooser fileChooser;public MusicPlayerGUI() {setTitle("音乐播放器");setSize(400, 200);setDefaultCloseOperation(EXIT_ON_CLOSE);setLayout(new FlowLayout());fileChooser = new JFileChooser();playButton = new JButton("播放");pauseButton = new JButton("暂停");stopButton = new JButton("停止");volumeSlider = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);add(fileChooser);add(playButton);add(pauseButton);add(stopButton);add(volumeSlider);playButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// 实现播放音乐的逻辑}});pauseButton.addActionListener(new ActionListener() { @Overridepublic void actionPerformed(ActionEvent e) {// 实现暂停音乐的逻辑}});stopButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// 实现停止音乐的逻辑}});volumeSlider.addChangeListener(new ChangeListener() { @Overridepublic void stateChanged(ChangeEvent e) {// 实现音量调节的逻辑}});}public static void main(String[] args) {SwingUtilities.invokeLater(new Runnable() {@Overridepublic void run() {new MusicPlayerGUI().setVisible(true);}});}}步骤3:音频处理和控制接下来,我们需要添加音频处理和控制的逻辑。
import java.awt.BorderLayout;import javax.media.Manager;import javax.media.NoPlayerException;import javax.media.Player;import javax.sound.sampled.AudioFormat;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.DataLine;import javax.sound.sampled.SourceDataLine;import javax.swing.ImageIcon;import javax.swing.JFileChooser;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JFrame;import javax.swing.JScrollPane;import java.awt.Rectangle;import javax.swing.JTable;import java.awt.Dimension;import javax.swing.JTextPane;import javax.swing.JScrollBar;import java.awt.List;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.io.IOException;import .MalformedURLException;import javax.swing.JButton;import javax.swing.filechooser.FileNameExtensionFilter; public class Hello extends JFrame implements ActionListener { private static final long serialVersionUID = 1L;private JPanel jContentPane = null;private List list = null;private JButton jButton = null;private Player play; // @jve:decl-index=0:private String str = null;private JButton jButton1 = null;private JButton jButton2 = null;private boolean b=false;private static SourceDataLine objSDL;private JButton jButton3 = null;/*** This is the default constructor*/public Hello() {super();ImageIcon backIcon = new ImageIcon(getClass().getResource("/image/hehe.jpg"));final JLabel backLabel = new JLabel(backIcon); // 创建背景标签backLabel.setSize(backIcon.getIconWidth(), backIcon.getIconHeight());backLabel.setLocation(0, 0);this.add(backLabel);initialize();}/*** This method initializes this** @return void*/private void initialize() {this.setSize(594, 346);this.setContentPane(getJContentPane());this.setTitle("达达播放器");setVisible(true);}/*** This method initializes jContentPane** @return javax.swing.JPanel*/// Start Output/*** 打开音频设备.* @param intFreq 采样率。
* @param iBits PCM位深(例如16)。
* @param channels 声道数*/private JPanel getJContentPane() {if (jContentPane == null) {jContentPane = new JPanel();jContentPane.setLayout(null);jContentPane.add(getList(), null);jContentPane.add(getJButton(), null);jContentPane.add(getJButton1(), null);jContentPane.add(getJButton2(), null);jContentPane.add(getJButton3(), null);}return jContentPane;}public void play(String str, List list) {File ff = new File(str + list.getSelectedItem());try {play = Manager.createPlayer(ff.toURL());} catch (NoPlayerException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (MalformedURLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}play.start();}/*** This method initializes list** @return java.awt.List*/private List getList() {if (list == null) {list = new List();list.setBounds(new Rectangle(67, 16, 425, 206));list.addItemListener(new java.awt.event.ItemListener() {public void itemStateChanged(java.awt.event.ItemEvent e) {if (play == null) {play(str, list);b=true;} else {play.close();play(str, list);}}});}return list;}/*** This method initializes jButton** @return javax.swing.JButton*/private JButton getJButton() {if (jButton == null) {jButton = new JButton();jButton.setBounds(new Rectangle(15, 244, 128, 31));jButton.setText("添加歌曲文件夹");jButton.addActionListener(this);}return jButton;}public void actionPerformed(ActionEvent e) {JFileChooser jchoose = new JFileChooser();jchoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONL Y);FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3", "MP3");jchoose.setMultiSelectionEnabled(true);// 选择文件夹jchoose.setFileFilter(filter);jchoose.setMultiSelectionEnabled(true);jchoose.showOpenDialog(this);if (jchoose.getSelectedFile() != null) {if (list != null)list.clear();File file = jchoose.getSelectedFile();str = jchoose.getCurrentDirectory()+ jchoose.getSelectedFile().getName() + "\\";File f[] = file.listFiles();for (int i = 0; i < f.length; i++) {if (f[i].getName().endsWith(".mp3"))list.add(f[i].getName());}}}/*** This method initializes jButton1** @return javax.swing.JButton*/private JButton getJButton1() {if (jButton1 == null) {jButton1 = new JButton();jButton1.setBounds(new Rectangle(155, 246, 115, 30));jButton1.setText("随机播放");jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) {// Thread Haha=new RadamPlay(list);// Haha.start();}});}return jButton1;}/*** This method initializes jButton2** @return javax.swing.JButton*/private JButton getJButton2() {if (jButton2 == null) {jButton2 = new JButton();jButton2.setBounds(new Rectangle(280, 246, 81, 30));jButton2.setText("暂停");jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) {if(play!=null){play.stop();}}});}return jButton2;}/*** This method initializes jButton3** @return javax.swing.JButton*/private JButton getJButton3() {if (jButton3 == null) {jButton3 = new JButton();jButton3.setBounds(new Rectangle(380, 247, 89, 29));jButton3.setText("播放");jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) {if(play!=null){play.start();}else{play(str, list);}}});}return jButton3;}public static void main(String args[]){new Hello();}} // @jve:decl-index=0:visual-constraint="47,10"。