Java音乐播放器源代码即结果显示
音乐播放器代码
音频播放器代码(1)<EMBED SRC="音乐文件地址">属性有:SRC="FILENAME" 设定音乐文件的路径AUTOSTART=TRUE/FALSE 是否要音乐文件传送完就自动播放,TRUE是要,FALSE是不要,默认为FALSELOOP=TRUE/FALSE 设定播放重复次数,LOOP=6表示重复6次,TRUE表示无限次播放,FALSE播放一次即停止。
STARTIME="分:秒" 设定乐曲的开始播放时间,如20秒后播放写为STARTIME=00:20VOLUME=0-100 设定音量的大小。
如果没设定的话,就用系统的音量。
WIDTH HEIGHT 设定控制面板的大小HIDDEN=TRUE 隐藏控制面板CONTROLS=CONSOLE/SMALLCONSOLE 设定控制面板样子例子:*************************************<html><head><title>播放音乐</title></head><body><EMBED SRC="midi.mid" autostart=true hidden=trueloop=true>作为背景音乐来播放。
</body></html>(2)wma格式音乐播放器代码自动播放代码<P align=center><EMBED name=Player34 pluginspage=/windows/mediapla yer/download/default.asp src=wma格式的歌曲地址width=200 height=50 type=application/x-mplayer2 showstatusbar="-1" AutoStart="-1" PlayCount="0" clicktoplay="-1"></P></EMBED>手动播放代码<P align=center><EMBED name=Player34 pluginspage=/windows/mediapla yer/download/default.asp src=wma格式的歌曲地址width=200 height=50 type=application/x-mplayer2 showstatusbar="-1" AutoStart="0" PlayCount="0" clicktoplay="-1"></P></EMBED>(3)mp3格式音乐播放器代码自动播放代码<P align=center><EMBED name=Player34pluginspage=/windows/mediapla yer/download/default.asp 格式的src=mp3歌曲地址width=200 height=50 type=application/x-mplayer2 showstatusbar="-1" AutoStart="-1" PlayCount="0" clicktoplay="-1"></P></EMBED>手动播放代码<P align=center><EMBED name=Player34 pluginspage=/windows/mediapla yer/download/default.asp src=mp3格式的歌曲地址width=200 height=50 type=application/x-mplayer2 showstatusbar="-1" AutoStart="0" PlayCount="0" clicktoplay="-1"></P></EMBED>(4)rm格式音乐播放器代码自动播放代码<P align=center><EMBED name=Player34 src=rm格式的歌曲地址width=200 height=50 type=application/octet-stream controls="StatusBar,ControlPanel" AutoStart="-1" numloop="0" loop="-1" clicktoplay="-1" nolabels="0" prefetch="0" shuffle="0" _extenty="847" _extentx="9657"></P></EMBED>手动播放代码<P align=center><EMBED name=Player34 src=rm格式的歌曲地址width=200 height=50 type=application/octet-stream controls="StatusBar,ControlPanel" AutoStart="0" numloop="0" loop="-1" clicktoplay="-1" nolabels="0" prefetch="0" shuffle="0" _extenty="847" _extentx="9657"></P></EMBED><html><head><meta name="generator" content="microsoft frontpage 6.0"> <meta name="progid" content="frontpage.editor.document"> <meta http-equiv="content-type" content="text/html; charset=gb2312"><title>插入音乐播放器</title></head>//只需要注意rows="*,21"这句就可以,21表示播放器占的高度为21个象素。
java音乐播放器实现代码
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上运⾏,⼀切正常,就是打包有点⼩问题暂时先说这些了,这个是我业余时间的项⽬,有什么不⾜的,⼤家都可以提出来。
一个简单音乐播放器代码
一个简单音乐播放器代码package bofang;import java.io.IOException;import com.example.bofang.R;import android.content.Intent;import android.media.MediaPlayer;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class Activity extends android.app.Activity{ private Button bt1;private Button bt2;private MediaPlayer player;//mediaplayer对象private boolean isplaying;//是否播放@Overrideprotected void onCreate(Bundle savedInstanceState) { // TODO自动生成的方法存根super.onCreate(savedInstanceState);setContentView(yout.activity);bt1=(Button)findViewById(R.id.bt1);bt2=(Button)findViewById(R.id.bt2);bt3.setOnClickListener(new OnClickListener() {bt1.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO自动生成的方法存根playOrpauseMusic();}});bt2.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO自动生成的方法存根stopMusic();}});init();}private void playOrpauseMusic() {// TODO自动生成的方法存根isplaying=player.isPlaying();if(isplaying){player.pause();bt1.setText("播放");}else{player.start();bt1.setText("暂停");//setimageresource(r.drawable.play)设置更换图片资源位置}bt2.setEnabled(true);}private void stopMusic() {// TODO自动生成的方法存根player.stop();bt1.setText("播放");bt2.setEnabled(false);try{ player.prepare();//为下次播放准备}catch(IllegalStateException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}player.seekTo(0);//定位音乐起始位置}private void init(){player=MediaPlayer.create(this,R.raw.cmsj);bt2.setEnabled(false);} }。
音乐播放器代码
<script language="javascript">var index=0,nums,mode=true;nums=20;var musices=new Array(nums);var list=new Array(nums);list[0]="01.当我孤独的时候还可以抱着你";list[1]="02.秋天不回来";list[2]="03.北极星的眼泪";list[3]="04.痛彻心扉";list[4]="05.就是爱你";list[5]="06.让我爱你";list[6]="07.六色彩虹";list[7]="08.划地为牢";list[8]="09.大城小爱";list[9]="10.会有天使替我爱你";list[10]="11.让我陪你";list[11]="12.受了点伤";list[12]="13.素敌だね";list[13]="14.寂静的夜晚里";list[14]="15.she";list[15]="16.7 Years and 50 Days";list[16]="17.Onlylove";list[17]="18.It's Only The Fairy Tal";list[18]="19.As long as U love me";list[19]="20.下川みくに悲しみに負け";musices[0]="/mp3/当我孤独的时候还可以抱着你.mp3";musices[1]="/Music/1c7efb9f33b04e48ac438acfefe67ad6/秋天不回来.mp3";musices[2]="/mp3/北极星的眼泪.mp3";musices[3]="/mxweb/zhangxh/网站用资料/音画季/歌曲/张栋梁-痛彻心扉.mp3";musices[4]="http://218.22.2.14/myweb/mp3/22.mp3";musices[5]="/1451/3/111.mp3";musices[6]="/huahua/caihong.mp3";musices[7]="/ising/song01/17_114.mp3";musices[8]="/file/dcxa.mp3";musices[9]="/hy.mp3";musices[10]="/cmsdata/batchmusic/20080123/JY9tVbmk.mp3"; musices[11]="/music/slds.mp3";musices[12]="/lshx.mp3";musices[13]="/123/ergemp3/xiaozhige.mp3";musices[14]="/uploadfile/2007-7/2007717103255911.mp3"; musices[15]="/xiaost/upfile/upfile/years.mp3";musices[16]="/music/Only%20Love.mp3";musices[17]="/Skyclass/Courseware/Blog/Blog235/070404198790.mp3"; musices[18]="/teacher/UploadFile/2007120205548710.mp3";musices[19]="/music/testone/bei.mp3";</script><object id="player" height=0 width=0 align=center classid=CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6item="24394746_3939749829_music"><param name="autoStart" value="false" /></object><label id="label_state">状态</label><input type="button" value="后退" onclick="javascript:index>0?index=index-1:index=0;player.URL=musices[index];mode==true?m ar.innerHTML=list[index]:mar.innerHTML=musices[index];player.controls.Play();"/><input type="button" value="暂停" onclick="javascript:player.controls.Pause();mar.innerHTML='音乐暂停中';"/><input type="button" value="停止" onclick="javascript:player.controls.Stop();mar.innerHTML='音乐已停止';"/><input type="button" value="播放" onclick="javascript:player.URL=musices[index];mode==true?mar.innerHTML=list[index]:mar.in nerHTML=musices[index];player.controls.Play();setInterval(function(){document.getElementByI d('label_current').innerHTML=player.controls.currentPositionString;document.getElementById('la bel_duration').innerHTML=player.currentMedia.durationString;},1000);setInterval(function(){swi tch(player.playState){case 1:label_state.innerHTML='停止';break;case 2:label_state.innerHTML='暂停';break;case 3:label_state.innerHTML='播放';break;case 4:label_state.innerHTML='前进';case 5:label_state.innerHTML='后退';case 6:label_state.innerHTML='缓冲';case 7:label_state.innerHTML='等待';case 8:label_state.innerHTML='完毕';break;case 9:label_state.innerHTML='连接';break;case 10:label_state.innerHTML='准备';break;default:break;}},1000)"/><!-匿名方法-><input type="button" value="前进" onclick="index<musices.length-1?index=index+1:index=musices.length-1;player.URL=musices[i ndex];mode==true?mar.innerHTML=list[index]:mar.innerHTML=musices[index];player.controls. Play();"/><marquee id="mar" width="100px">歌曲名称</marquee><input name="play_id" type="button" value="静音" onclick="javascript:player.settings.mute=!player.settings.mute;player.settings.mute?mar.innerHT ML='静音中':(mode==true?mar.innerHTML=list[index]:mar.innerHTML=musices[index]);"/><input name="play_id" type="button" value="-" onclick="javascript:player.settings.volume=player.settings.volume-10;volume_id.innerHTML=pla yer.settings.volume;"/><label id="volume_id" width="50px">50</label><input name="play_id" type="button" value="+" onclick="javascript:player.settings.volume=player.settings.volume+10;volume_id.innerHTML=pl ayer.settings.volume;"/"/><label id="label_current">00:00</label><label id="label_duration">00:00</label><input name="play_id" type="button" value="循环" onclick="javascript:player.settings.playCount=999;player.settings.autostart=true;"/><input type="button" value="切换" onclick="javascript:mode=!mode;mode==true?mar.innerHTML=list[index]:mar.innerHTML=mus ices[index];"/><input name="play_id" type="button" value="版权" onclick="javascript:window.alert('狂影[url=]论坛[/url] 2.4')"/><a id="aa" title="歌曲列表" onclick="javascript:this.innerText=='+'?label_id.style.display='block':label_id.style.display='none' ;this.innerText=='+'?label_id.innerText='列表添加中..':label_id.innerText='';this.innerText=='+'?this.innerText='-':this.innerText='+';">+</a><label id="label_id"></label>增加功能:前进后退歌曲多列表模式切换增加播放时间播放总时间功能歌曲列表功能添加中..状态栏(缓冲在内10种状态)<style type="text/css">#label_id{background-color:#99FFFF;width:600px;height:300px;display:none;}</style>。
音乐播放器源代码
P align=center><TABLE borderColor=#4f3256 align=centerbackground=/zh_cn/home4u/sucai/gifanimation/line/0022.gifborder=1><TBODY><TR><TD style="FILTER: alpha(opacity=100,style=3)"> <P align=center><EMBED src=width=369 height=39type=audio/mpeg loop="-1" autostart="ture"volume="0"></P></TD></TR></TBODY></TABLE></P>autostart="true"中true或1表示自动播放,false或0表示手动播放loop="true" 中的true或1表示重复播放,false或0表示只播放一次width= height= 中的数字分别表示播放器的宽度和高度=0表示隐藏播放器EnableContextMenu="0" 禁右键ShowStatusBar="1" (带显示文件播放信息)=======================================================隐藏(hidden=true)播放器(不循环)<EMBED src=音乐网址hidden=true type=audio/x-ms-wma AUTOSTART="1">-----------------------------------------------------------隐藏(hidden=true)播放器(循环)<EMBED src=音乐网址hidden=true type=audio/mpeg AUTOSTART="1" loop="-1"> ---------------------------------------------------------------黑色[style="FILTER: xray()"]循环[loop="-1"]播放器<EMBED style="FILTER: xray()" src=音乐网址width=360 height=30type=audio/mpeg volume="0" autostart="true" loop="-1">--------------------------------------------------------------------------------浅兰色循环(loop="-1")播放器<EMBED src=音乐网址width=300 height=45 type=audio/mpeg loop="-1"autostart="true" volume="0">--------------------------------------------------------------------------掩饰自动播放器<TABLE style="FILTER: Alpha(Opacity=100, FinishOpacity=0, Style=2, StartX=20, StartY=40, FinishX=0, FinishY=0)gray(); WIDTH: 200px; HEIGHT: 83px"><TBODY><TR><TD><EMBED src=音乐网址width=200 height=40 type=audio/mpeg panel="0" autostart="true" loop="true"></TD></TR></TBODY></TABLE>-------------------------------------连播放时选择曲目的播放器<EMBEDpluginspage=/windows/mediaplayer/download/default.as p width=400 height=172 type=application/x-mplay er2 FileName="音乐网址" SHOWCONTROLS="1" SHOWSTATUSBAR="1" SHOWDISPLAY="1" SHOWGOTOBAR="1" AUTOSTART="true" PlayCount="1">----------------------------------------------------------------------------------------------显示曲名的黑色带彩自动播放器<EMBED style="FILTER: invert()" src=音乐网址width=320 height=45type=audio/x-ms-wma ShowStatusBar="1" loop="true" autostart="true">-------------------------------------------------------------------------显示曲名的灰白色面板<EMBED style="FILTER: Gray()" src="链接地址" width=300 height=69type=application/x-mplayer2 loop="-1" showcontrols="1" ShowDisplay="0" ShowStatusBar="1" autostart="1"></EMBED>------------------------------------------灰白面板<embed style="FILTER: Gray()" src=链接地址width=300 height=45 loop="-1" autostart="true"></EMBED>---------------------------------------------------------------(带显示文件播放信息)<EMBED src="链接地址" width=300 height=69 type=application/x-mplay er2loop="-1" showcontrols="1" ShowDisplay="0" ShowStatusBar="1"autostart="1"></EMBED>-----------------------------------------------黑色带彩棕色面板<EMBED style="FILTER: invert()" src=链接地址width=300 height=45 loop="-1" autostart="true"></EMBED>---------------------------------------------------------------------浅紫播放器<TABLE borderColor=#4F3256background=/DownloadImg/2010/09/0718/5119955_3.jpg border=1><TBODY><TR><TD style="FILTER: alpha(opacity=50,style=3)"><P align=center><EMBED src=音乐网址width=300 height=25 type=audio/mpeg loop="-1" autostart="false" volume="0"></P></TD></TR></TBODY></TABLE>----------------------------------------------------------------------------------------------粉色<TABLE borderColor=navybackground=/UploadFile/2005-9/200592522275884778.jpg border=0><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="0" volume="0"></P></TD></TR></TBODY></TABLE>------------------------------------------------------------------------------------黄色闪光<TABLE style="BORDER-RIGHT: #000000 3px dashed; BORDER-TOP: #000000 3px dashed; BORDER-LEFT: #000000 3px dashed; BORDER-BOTTOM: #000000 3px dashed" cellSpacing=0 cellPadding=0 bgColor=#00000><TBODY><TR><TD><TABLE borderColor=navybackground=/s-helpSite/domName/nxm/20041114123131568.gi f border=0><TBODY><TR><TD style="FILTER: alpha(opacity=50,style=3)"><P align=center><EMBED src=音乐网址width=400 height=35 type=audio/mpeg loop="-1" autostart="0" loop="-1"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>--------------------------------------------------------------------------------蓝色闪光<TABLE borderColor=#dee4fe cellSpacing=3 cellPadding=0background=/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=400 height=35 type=audio/mpeg volume="0" autostart="false" loop="-1"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>-------------------------------------------------------------------------花边黑色<TABLE style="BORDER-RIGHT: #000000 3px dashed; BORDER-TOP: #000000 3px dashed; BORDER-LEFT: #000000 3px dashed; BORDER-BOTTOM: #000000 3px dashed" cellSpacing=0 cellPadding=0 bgColor=#00000><TBODY><TR><TD><TABLE borderColor=#000000 align=center border=1><TBODY><TR><TD><P align=center><EMBED style="FILTER: Xray" src=音乐网址width=400 height=35 type=audio/mpeg volume="0" autostart="false" loop="-0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>-----------------------------------------------------------------------------------------------------粉色花边<TABLE style="BORDER-RIGHT: #ff69b4 3px dotted; BORDER-TOP: #ff69b4 3px dotted; BORDER-LEFT: #ff69b4 3px dotted; BORDER-BOTTOM: #ff69b4 3px dotted" cellSpacing=0 cellPadding=0 align=center bgColor=white><TBODY><TR><TD><TABLE borderColor=#ff69b4 align=center bgColor=#ffccf5 border=2><TBODY><TR><TD style="FILTER: alpha(opacity=100,style=3)"><P align=center><EMBED src=音乐网址width=300 height=25 type=audio/mpeg volume="0" autostart="false" loop="-0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE>-------------------------------------------------------------------------------------------禁右键播放器<EMBED style="BORDER-RIGHT: silver 1px solid; BORDER-TOP: silver 1px solid; BORDER-LEFT: silver 1px solid; BORDER-BOTTOM: silver 1px solid" src=音乐网址width=200 height=40 type=audio/x-mplayer2 console="video" showstatusbar="0" EnableContextMenu="0" volume="0" autostart="0" loop="-1">---------------------------------------------------------------------------------上下移动<MARQUEE style="LEFT: 230px; ; TOP: 300px" scrollAmount=1 scrollDelay=200 direction=up behavior=alternate width=300 height=400><br><MARQUEE scrollAmount=1 scrollDelay=100 behavior=alternate><br><TABLE style="FILTER: progid:DXImageTransform.Microsoft.Shadow(color:#7ec0ee ,direction:145,strengt h:20)" cellSpacing=0 cellPadding=0 border=1><br><TBODY><br><TR><br><TD><EMBED style="FILTER: gray()" src=音乐网址width=200 height=20type=audio/mpeg showstatusbar="1" volume="0" loop="-1" autostart="1"></TD></TR></TBODY></TABLE></MARQUEE></MARQUEE>-------------------------------------------------------------------(显示文件标签信息)蓝色<DIV><EMBED src="链接地址" loop="-1" width=300 height=140 balance="true" showpositioncontrols="true" showtracker="true" showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true" autostart="true" animationatstart="true" transparentatstart="true"></EMBED></div>--------------------------------------------------(显示文件标签信息)灰白<DIV><EMBED style="FILTER: Gray()" src="链接地址" loop="-1" width=300height=140 balance="true" showpositioncontrols="true" showtracker="true" showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true"autostart="true" animationatstart="true"transparentatstart="true"></EMBED></div>----------------------------------------------------(显示文件标签信息)黑彩<DIV><EMBED style="FILTER: invert()" src="链接地址" loop="-1" width=300 height=140 balance="true" showpositioncontrols="true" showtracker="true"showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true"autostart="true" animationatstart="true"transparentatstart="true"></EMBED></div>-----------------------------------------------------------(显示文件标签信息)黑<DIV><EMBED style="FILTER: xray()" src="链接地址" loop="-1" width=300height=140 balance="true" showpositioncontrols="true" showtracker="true" showaudiocontrols="true" showcontrols="true" showstatusbar="true" showdisplay="true" displaysize="0" volume="100" autosize="true"autostart="true" animationatstart="true"transparentatstart="true"></EMBED></div>===================================================连放<EMBED style="FILTER: Gray()" src=音乐网址width=500 height=35type=audio/x-ms-wma controls="StatusBar,TACCtrl,ControlPanel" border="0" autostart="1" playcount="0" showtracker="1" volume="0"></EMBED>=========================================================图片播放器!<TABLE style="FILTER: alpha(opacity=100 Style=0 FinishOpacity=100)" borderColor=#000000 height=249 cellSpacing=0 cellPadding=0 width=314 background=/DownloadImg/2010/09/0718/5119955_4.gif border=0><TBODY><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 loop="-1" autostart="1" volume="0"></P></TD></TR></TBODY></TABLE>=================================================以上效果分见如下::为免各效果同时播放,以下autostart=0autostart="true"中true或1表示自动播放,false或0表示手动播放loop="true" 中的true或1表示重复播放,false或0表示只播放一次width= height= 中的数字分别表示播放器的宽度和高度=0表示隐藏播放器EnableContextMenu="0" 禁右键ShowStatusBar="1" (带显示文件播放信息)=======================================================隐藏(hidden=true)播放器(不循环)src="/LIU/all_about_you.wma" hidden="true"type="audio/x-ms-wma" allowscriptaccess="never" autostart="0">-----------------------------------------------------------隐藏(hidden=true)播放器(循环)src="/LIU/all_about_you.wma" hidden="true"type="audio/mpeg" allowscriptaccess="never" autostart="0" loop="-1">---------------------------------------------------------------黑色[style="FILTER: xray()"]循环[loop="-1"]播放器style="FILTER: xray()" src="/LIU/all_about_you.wma" width="360" height="30" type="audio/mpeg" allowscriptaccess="never"volume="0" autostart="0" loop="-1">--------------------------------------------------------------------------------浅兰色循环(loop="-1")播放器src="/LIU/all_about_you.wma" width="300" heigh t="45" type="audio/mpeg" allowscriptaccess="never" loop="-1" autostart="0"volume="0">--------------------------------------------------------------------------掩饰自动播放器src="/LIU/all_about_you.wma"width="200" height="40" type="audio/mpeg"allowscriptaccess="never" panel="0" autostart="0"loop="true">-------------------------------------连播放时选择曲目的播放器pluginspage="/windows/mediaplayer/download/default.a sp" width="400" height="172" type="application/x-mplayer2"allowscriptaccess="never"filename="/LIU/all_about_you.wma" showcontrols="1" showstatusbar="1" showdisplay="1" showgotobar="1" autostart="0"playcount="1">----------------------------------------------------------------------------------------------显示曲名的黑色带彩自动播放器style="FILTER: invert()" src="/LIU/all_about_you.wma" width="320" height="45" type="audio/x-ms-wma" allowscriptaccess="never" showstatusbar="1" loop="0" autostart="0">-------------------------------------------------------------------------显示曲名的灰白色面板style="FILTER: Gray()" src="/LIU/all_about_you.wma" width="300" height="69" type="application/x-mplay er2" allowscriptaccess="never" loop="-1" showcontrols="1" showdisplay="0" showstatusbar="1" autostart="0"> ------------------------------------------灰白面板style="FILTER: Gray()" src="/LIU/all_about_you.wma" width="300" height="45" type="audio/x-ms-wma" allowscriptaccess="never"loop="-1" autostart="0">---------------------------------------------------------------(带显示文件播放信息)src="/LIU/all_about_you.wma" width="300" height="69" type="application/x-mplay er2" allowscriptaccess="never" loop="-1"showcontrols="1" showdisplay="0" showstatusbar="1" autostart="0">-----------------------------------------------黑色带彩棕色面板style="FILTER: invert()" src="/LIU/all_about_you.wma" width="300" height="45" type="audio/x-ms-wma" allowscriptaccess="never"loop="-1" autostart="0"><CENTER><TABLE style="BORDER-RIGHT: #f1dda1 2px ridge; BORDER-TOP: #bdb76b 2px ridge; BORDER-LEFT: #f1dda1 2px ridge; BORDER-BOTTOM: #bdb76b 2px ridge; BACKGROUND-COLOR: white" borderColor=#ffffff cellPadding=0width=300 align=centerbackground=/fileuploaddir/4B2686448.4.gifborder=0><TBODY><TR><TD width=300 height=20 cellPadding="0"cellSpacing="0"><TABLE align=center border=0><TBODY><TR><TDstyle="FILTER: alpha(opacity=60,style=3)"><P align=center><EMBED style="FILTER: invert(); WIDTH: 290px; HEIGHT: 28px" src=/Q/.Wma type=audio/x-ms-wma autostart="true"loop="-1"volume="0"></P></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></CENTER一、音乐播放器源代码(神采飞扬版)P align=center><TABLE borderColor=#4f3256 align=center background=http://tech.china.com/zh_cn/home4u/sucai/gifanimation/line/0022.gif border=1><TBODY><TR><TD style="FILTER: alpha(opacity=100,style=3)"><P align=center><EMBED src=width=369 height=39type=audio/mpeg loop="-1" autostart="ture" volume="0"></P></TD></TR> </TBODY></TABLE></P>二、具体操作步骤1、在“BLOG发表文章”网页里,也即是写文章的网页里,写好文字后,选中文字上方的“查看HTML源代码”项(选项前的方框内出现√则为选中),这时我们看见原来的文字成了汉字、英文字母和一些诸如<、/、=等符号组成的乱码。
音乐播放器代码
target="_blank"><font
href="/?pid=mm_34029538_3439848_11149737&tb_lm_id=l_sczl_sogou_cyg j" target="_blank"><font color=slategray size=2>一淘专享
size=2>TOP10
店 铺 </a> <a
href="/"
target="_blank"><font color=slategray size=2>时光网址导航</a> <a
href="/?tracker_u=1787&uid=91520851657&website_id=521945"
代 码 二 : <div><embed height="620" allownetworking="internal" width="960" allowscriptaccess="never" loop="-1" invokeurls="false" src="/yyzb" type="audio/mpeg" wmode="transparent"><br/></div>
<meta name="keywords" content="音乐网">
java 实现音乐播放器的简单实例
java 实现音乐播放器的简单实例这篇文章主要介绍了java 实现音乐播放器的简单实例的相关资料,希望通过本文能帮助到大家,实现这样的功能,需要的朋友可以参考下:java 实现音乐播放器的简单实例实现效果图:代码如下:package cn.hncu.games;import java.applet.Applet;import java.applet.AudioClip;import java.awt.Color;import java.awt.Font;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.io.File;import .URL;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.ListModel;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;public class MusicPlayer extends JFrame{//显示(歌曲名称)播放状态的标签JLabel songNameLabel = null;//四个播放功能键按钮JButton btnLast = null; //上一曲JButton btnPlay = null; //播放/停止JButton btnNext = null; //下一曲JButton btnLoop = null; //循环//歌曲列表JList songsList = null;AudioClip songs[] = null;AudioClip currentSong = null;int index=0; //当前歌曲在JList中的位置(序号)//歌曲文件名数组---StringString[]strSongNames={ "song1.wav","song2.wav","song3.wav","song4.wav","song5 .wav","song6.wav" };final String DIR="songs\\";//播放音乐的线程Thread playerThread=null;boolean isPlayOrStop = true;//true代表播放状态boolean isLoop = false; //是否为循环状态public MusicPlayer() {super("音乐播放器");setBounds(300, 50, 310, 500);setDefaultCloseOperation(EXIT_ON_CLOSE);setLayout(null);//hello();//显示(歌曲名称)播放状态的标签songNameLabel = new JLabel();Font songNameFont = new Font("黑体",Font.ITALIC,18); songNameLabel.setFont(songNameFont);songNameLabel.setText("我的音乐播放器");songNameLabel.setBounds(10, 10, 300, 40);getContentPane().add(songNameLabel);//四个播放功能键按钮btnLast = new JButton();btnPlay = new JButton();btnNext = new JButton();btnLoop = new JButton();//位置大小btnLast.setBounds(10, 70, 50, 40);btnPlay.setBounds(70, 70, 50, 40);btnNext.setBounds(130, 70, 50, 40);btnLoop.setBounds(190, 70, 50, 40);//设置图片btnLast.setIcon( new ImageIcon("images2/1.png"));btnPlay.setIcon( new ImageIcon("images2/2.png"));btnNext.setIcon( new ImageIcon("images2/3.png"));btnLoop.setIcon( new ImageIcon("images2/4.png"));//添加到框架getContentPane().add(btnLast);getContentPane().add(btnPlay);getContentPane().add(btnNext);getContentPane().add(btnLoop);//添加监听MyMouseListener mml = new MyMouseListener();btnLast.addMouseListener(mml);btnPlay.addMouseListener(mml);btnNext.addMouseListener(mml);btnLoop.addMouseListener(mml);//歌曲列表的标题JLabel listLabel = new JLabel("播放列表");listLabel.setBounds(10, 120, 100, 30);Font listLabelFont = new Font("黑体",Font.BOLD,16);listLabel.setFont(listLabelFont);getContentPane().add(listLabel);//歌曲列表/*songsList = new JList();songsList.setBounds(10, 150, 250, 300);songsList.setBackground(Color.CYAN);//把所有歌曲名逐个添加到List中//songsList.setListData(strSongNames);for(int i=0;i<strSongNames.length;i++){DefaultListModel dm = (DefaultListModel)songsList.getModel(); dm.add(i,strSongNames[i]);}getContentPane().add(songsList);*/DefaultListModel lm = new DefaultListModel();songsList = new JList(lm);songsList.setBounds(10, 150, 250, 300);songsList.setBackground(Color.CYAN);//把所有歌曲名逐个添加到List中//songsList.setListData(strSongNames);songs = new AudioClip[strSongNames.length];for(int i=0;i<strSongNames.length;i++){lm.add(i,strSongNames[i]);songs[i] = loadSound(strSongNames[i]);}getContentPane().add(songsList);//lm.remove(3);//对JList控件的监听技术实现songsList.addListSelectionListener(new ListSelectionListener() { @Overridepublic void valueChanged(ListSelectionEvent e) {currentSong.stop();index = songsList.getSelectedIndex();isPlayOrStop = true;playerThread = new Thread( new MusicRun() );playerThread.start();}});//单开一个线程,专用于播放音乐playerThread = new Thread( new MusicRun() );playerThread.start();setVisible(true);}private AudioClip loadSound(String fileName) {try {URL url = new URL("file:songs\\"+fileName);AudioClip au = Applet.newAudioClip(url);return au;} catch (Exception e) {e.printStackTrace();}return null;}//讲解音乐播放的基本技术private void hello() {try {File f = new File("songs\\song1.wav");URL url = f.toURI().toURL();//URL url = new URL("file:songs\\song1.wav"); AudioClip au = Applet.newAudioClip(url);au.play();//au.loop();//au.stop();} catch (Exception e) {e.printStackTrace();}}private class MyMouseListener extends MouseAdapter{ @Overridepublic void mouseClicked(MouseEvent e) {JButton btn = (JButton) e.getSource();currentSong.stop();if(btn==btnPlay){isPlayOrStop = !isPlayOrStop;}else if(btn==btnLast){index--;if(index<0){index = strSongNames.length-1;}//isPlayOrStop=true;}else if(btn==btnNext){index++;index = index%strSongNames.length;}else if(btn==btnLoop){isLoop = !isLoop;}if(isPlayOrStop){//播放playerThread = new Thread( new MusicRun() );playerThread.start();}else{//停止songsList.setSelectedIndex(index);songNameLabel.setText("停止播放:"+strSongNames[index]); btnPlay.setIcon( new ImageIcon("images2/2.png"));}}}private class MusicRun implements Runnable{@Overridepublic void run() {currentSong = songs[index];if(isLoop){currentSong.loop();songNameLabel.setText("循环播放:"+strSongNames[index]); }if (isPlayOrStop) {currentSong.play();}//在播放列表中选定当前歌曲songsList.setSelectedIndex(index);//把播放按钮的图标切换成“停止”btnPlay.setIcon( new ImageIcon("images2/5.png"));if(!isLoop){songNameLabel.setText("正在播放:"+strSongNames[index]); }}}public static void main(String[] args) {new MusicPlayer();}}。
Java综合实验-简易音乐播放器-实验报告
Java综合实验实验报告一、实验要求根据下列描述:为某音乐爱好者开发音乐管理系统,该系统可以为音乐爱好者对已有的音乐信息检索、音乐播放、音乐收藏进行管理。
(1)音乐检索:对指定音乐名称进行检索,获取音乐的基本信息。
(2)音乐播放:对已有音源的音乐进行播放音乐收藏:对喜欢的音乐进行收藏管理,记录音源的位置等;二、核心思想利用MVC模式,结合javafx和SceneBuilder开发音乐管理系统三、实验原理四、实验环境Window 11、JDK-17、Intellij IDEA、JavaFX Scene Builder 2.0五、核心代码:1.业务逻辑:①User类package prehensiveExperiment.logic;import java.util.ArrayList;import java.util.List;/*** 用户类* 这个类记录了用户信息:账号、密码以及自己维护的音乐收藏*/public class User {private String account;private String password;private List<Music> musicCollection;public User(String account, String password) {this.account = account;this.password = password;musicCollection = new ArrayList<>();}public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}/*** 获取音乐收藏* @return musicCollection*/public List<Music> getMusicCollection() {return musicCollection;}/*** 收藏歌曲* @param music*/public void addMusic(Music music){musicCollection.add(music);}/*** 取消收藏* @param music*/public void deleteMusic(Music music){musicCollection.remove(music);}@Overridepublic String toString() {return "User{" +"account='" + account + '\'' +", password='" + password + '\'' +", musicCollection=" + musicCollection +'}';}}②Music类:package prehensiveExperiment.logic;/*** 音乐类* 这个类记录了歌曲的信息:歌曲名、歌手、歌曲时长、大小、发行时间、专辑*/public class Music implements Comparable<Music>{private String name;private String singer;private String totalTime;private String size;private String startTime;private String album;public Music(String name, String singer, String totalTime, String size, String startTime, String album) { = name;this.singer = singer;this.totalTime = totalTime;this.size = size;this.startTime = startTime;this.album = album;}public String getName() {return name;}public void setName(String name) { = name;}public String getSinger() {return singer;}public void setSinger(String singer) {this.singer = singer;}public String getTotalTime() {return totalTime;}public void setTotalTime(String totalTime) {this.totalTime = totalTime;}public String getSize() {return size;}public void setSize(String size) {this.size = size;}public String getStartTime() {return startTime;}public void setStartTime(String startTime) {this.startTime = startTime;}public String getAlbum() {return album;}public void setAlbum(String album) {this.album = album;}/*** 默认按歌手排序* @param o* @return*/@Overridepublic int compareTo(Music o){return pareTo(o.singer);}@Overridepublic String toString() {return "Music{" +"name='" + name + '\'' +", singer='" + singer + '\'' +", totalTime='" + totalTime + '\'' +", size='" + size + '\'' +", startTime='" + startTime + '\'' +", album='" + album + '\'' +'}';}}③MusicSys类:package prehensiveExperiment.logic;import java.io.File;import java.io.FileNotFoundException;import java.util.ArrayList;import parator;import java.util.List;import java.util.Scanner;/*** 音乐管理系统* 这个类维护了用户音乐收藏、本地音乐以及播放器的常规操作*/public class MusicSys {private Music currentMusic;private int index;//当前播放音乐的索引值private String state;private double volume;private List<User> users;//用户private int index2;//当前登录用户的索引值private List<Music> musics;//本地音乐private static MusicSys instance = null;//单例模式/*** 构造函数* 分别调用createUser()和createMusic()录入用户和音乐信息* 播放器初始状态:默认关闭(state = OFF),如果打开默认播放第一首歌(index=0),音量调至一半(volume = 0.5)* @throws FileNotFoundException*/private MusicSys() throws FileNotFoundException {users = new ArrayList<>();musics = new ArrayList<>();createUser();createMusic();index = 0;currentMusic = musics.get(index);state = "OFF";volume = 0.5;}/*** 单一工厂* @return instance* @throws FileNotFoundException*/public static MusicSys getInstance() throws FileNotFoundException {if(instance == null)instance = new MusicSys();return instance;}/*** 这个方法通过扫描事先写好的User.txt文件,将用户信息一条条录入。
基于java的音乐播放器的设计(源代码+实验报告)
主类MUSICPLAYER类:import java.util.*;import javax.swing.JSlider;import java.awt.BorderLayout;import java.awt.FlowLayout;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import javax.media.ControllerEvent;import javax.media.ControllerListener;import javax.media.EndOfMediaEvent;import javax.media.Manager;import javax.media.MediaLocator;import javax.media.NoPlayerException;import javax.media.Player;import javax.media.PrefetchCompleteEvent;import javax.media.Time;import javax.swing.ButtonGroup;import javax.swing.DefaultListModel;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JRadioButtonMenuItem;import javax.swing.JScrollBar;import javax.swing.JScrollPane;import javax.swing.filechooser.FileNameExtensionFilter;public class MusicPlayer implements ActionListener, Serializable,ControllerListener {private static final long serialVersionUID = 1L;private JFrame frame = null;private JPanel controlPanel = null;private JButton btnPlay = null;private JButton btnPre = null;private JButton btnNext = null;private JScrollPane listPane = null;private JList list = null;private DefaultListModel listModel = null;private JMenuBar menubar = null;private JMenu menuFile = null, menuAbout = null, menuMode = null;private JMenuItem itemOpen, itemOpens, itemExit, itemAbout;private JRadioButtonMenuItem itemSingle, itemSequence ,itemRandom;private ListItem currentItem = null;private static Player player = null;private boolean isPause = false;private int mode;private int currentIndex;private ImageIcon iconPlay = new ImageIcon("d:\\1.jpg");private ImageIcon iconPre = new ImageIcon("d:\\3.jpg");private ImageIcon iconNext = new ImageIcon("d:\\2.jpg");private ImageIcon iconPause = new ImageIcon("d:\\4.jpg");public static void main(String[] args){new MusicPlayer();}public MusicPlayer(){init();}public void init(){frame = new JFrame();frame.setTitle("音乐播放器");frame.setSize(400, 300);frame.setResizable(false);frame.setLocationRelativeTo(null);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);menubar = new JMenuBar();menuFile = new JMenu("文件");menuAbout = new JMenu("关于");menuMode = new JMenu("播放模式");itemOpen = new JMenuItem("添加文件");itemOpens = new JMenuItem("添加文件夹");itemExit = new JMenuItem("退出");itemAbout = new JMenuItem("关于");itemOpen.addActionListener(this);itemOpens.addActionListener(this);itemExit.addActionListener(this);itemAbout.addActionListener(this);itemSequence = new JRadioButtonMenuItem("顺序播放"); itemSequence.setSelected(true);itemSingle = new JRadioButtonMenuItem("单曲循环"); itemSequence.addActionListener(this);itemRandom = new JRadioButtonMenuItem("随机播放"); itemRandom.addActionListener(this);itemSingle.addActionListener(this);ButtonGroup bg = new ButtonGroup();bg.add(itemRandom);bg.add(itemSequence);bg.add(itemSingle);menuFile.add(itemOpen);menuFile.add(itemOpens);menuFile.add(itemExit);menuAbout.add(itemAbout);menuMode.add(itemSequence);menuMode.add(itemSingle);menuMode.add(itemRandom);menubar.add(menuFile);menubar.add(menuAbout);menubar.add(menuMode);frame.setJMenuBar(menubar);frame.setLayout(new BorderLayout());controlPanel = new JPanel();controlPanel.setLayout(new FlowLayout());btnPlay = new JButton(iconPlay);btnPre = new JButton(iconPre);btnNext = new JButton(iconNext);btnPlay.addActionListener(this);btnPre.addActionListener(this);btnNext.addActionListener(this);controlPanel.add(btnPre);controlPanel.add(btnPlay);controlPanel.add(btnNext);listPane = new JScrollPane();listModel = load();list = new JList(listModel);if (list.getSelectedIndex() == -1 && listModel.size() > 0){currentItem = (ListItem) listModel.get(0);list.setSelectedIndex(0);currentIndex=0;}listPane.getViewport().add(list);list.addMouseListener(new MouseAdapter(){public void mouseClicked(MouseEvent e){if (e.getClickCount() == 2){if(player!=null){player.close();btnPlay.setIcon(iconPlay);}currentIndex = list.locationToIndex(e.getPoint());currentItem = (ListItem) listModel.get(currentIndex);list.setSelectedIndex(currentIndex);play();}}});frame.setLayout(new BorderLayout());frame.add(controlPanel, BorderLayout.NORTH);frame.add(listPane, BorderLayout.CENTER);frame.setVisible(true);};public void actionPerformed(ActionEvent e){if (e.getSource() == itemOpen){// add filesJFileChooser jfc = new JFileChooser();FileNameExtensionFilter filter = new FileNameExtensionFilter("音乐文件", "mp3", "wav");jfc.setFileFilter(filter);jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);jfc.setMultiSelectionEnabled(true);if (jfc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){File[] files = jfc.getSelectedFiles();for (File f : files){ListItem item = new ListItem(f.getName(), f.getAbsolutePath());listModel.addElement(item);}}}else if (e.getSource() == itemOpens){// add files in a directoryJFileChooser jfc = new JFileChooser();jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);if (jfc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){File directory = jfc.getSelectedFile();File[] files = directory.listFiles(new java.io.FileFilter(){public boolean accept(File f){if (f.getName().toLowerCase().endsWith(".mp3")|| f.getName().toLowerCase().endsWith(".wav"))return true;return false;}});for (File file : files){ListItem item = new ListItem(file.getName(), file.getAbsolutePath());listModel.addElement(item);}save(listModel);}}else if (e.getSource() == itemExit){System.exit(0);}else if (e.getSource() == itemAbout){JOptionPane.showMessageDialog(frame, "作者:陆鑫");}else if (e.getSource() == btnPlay){// play or pauseplay();}else if (e.getSource() == btnPre){pre();}else if (e.getSource() == btnNext){// next musicnext();}else if (e.getSource() == itemSequence){mode = 0;}else if (e.getSource() == itemSingle){mode = 1;}else if (e.getSource() == itemRandom){mode = 2;}}// play control/*** 播放*/public void play(){if (btnPlay.getIcon() == iconPlay){if (isPause){player.start();System.out.println("暂停结束");isPause = false;}else{try{player = Manager.createPlayer(new MediaLocator("file:"+ currentItem.getPath()));player.addControllerListener(this); // 提取媒体内容player.prefetch();}catch (NoPlayerException e1){e1.printStackTrace();}catch (IOException e1){e1.printStackTrace();}}btnPlay.setIcon(iconPause);}else{player.stop();isPause = true;System.out.println("暂停");btnPlay.setIcon(iconPlay);}}public void next(){if (currentIndex == listModel.getSize() - 1){currentIndex = 0;}else{currentIndex++;}currentItem = (ListItem) listModel.get(currentIndex);list.setSelectedIndex(currentIndex);Point p = list.indexToLocation(currentIndex);JScrollBar jScrollBar = listPane.getVerticalScrollBar();// 获得垂直转动条jScrollBar.setValue(p.y);// 设置垂直转动条位置btnPlay.setIcon(iconPlay);if (player != null)player.close();isPause = false;play();}public void rand(){list.setSelectedIndex((int)(Math.random()%(listModel.getSize()-1)));Pointp=list.indexToLocation((int)(Math.random()%(listModel.getSize()-1)));JScrollBar jScrollBar = listPane.getVerticalScrollBar();jScrollBar.setValue(p.y);btnPlay.setIcon(iconPlay);if (player != null)player.close();isPause = false;play();}public void pre(){if (currentIndex == 0){currentIndex = listModel.getSize() - 1;}else{currentIndex--;}currentItem = (ListItem) listModel.get(currentIndex);list.setSelectedIndex(currentIndex);Point p = list.indexToLocation(currentIndex);JScrollBar jScrollBar = listPane.getVerticalScrollBar();// 获得垂直转动条jScrollBar.setValue(p.y);// 设置垂直转动条位置btnPlay.setIcon(iconPlay);if (player != null){player.close();}isPause = false;play();}// end play controlpublic DefaultListModel load(){File file = new File("list.lst");DefaultListModel dlm = new DefaultListModel();if (file.exists()){try{ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));Integer size = (Integer) ois.readObject();if (size != 0){for (int i = 0; i < size; i++){ListItem item = (ListItem) ois.readObject();dlm.addElement(item);}}ois.close();return dlm;}catch (FileNotFoundException e){e.printStackTrace();}catch (IOException e){e.printStackTrace();}catch (ClassNotFoundException e){e.printStackTrace();}}return dlm;}public void save(DefaultListModel dlm){try{ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("list.lst")));Integer size = dlm.getSize();oos.writeObject(size);for (int i = 0; i < size; i++){ListItem item = (ListItem) dlm.get(i);oos.writeObject(item);}oos.close();}catch (Exception e){e.printStackTrace();}}public void controllerUpdate(ControllerEvent e) {if (e instanceof EndOfMediaEvent){if (mode == 0){// 顺序播放System.out.println("顺序播放");next();}else if (mode == 1){ // 单曲循环System.out.println("播放结束");player.setMediaTime(new Time(0));System.out.println("单曲循环");player.start();}else if (mode == 2){System.out.println("随机播放");rand();}return;}// 当提取媒体的内容结束if (e instanceof PrefetchCompleteEvent){System.out.println("开始播放");player.start();return;}}}LISTITEM类import java.io.Serializable;public class ListItem implements Serializable{private static final long serialVersionUID = 1L;private String name;private String path;public ListItem(){}public ListItem(String name, String path){ = name;this.path = path;}public String getName(){return name;}public void setName(String name){ = name;}public String getPath(){return path;}public void setPath(String path){this.path = path;}public String toString(){return name;}}基于java的音乐播放器的设计摘要:在信息,技术高速发展的今天,多媒体技术也越来越受到人们的重视。
音频播放器源代码
音频播放器源代码1。
可以自动调节长度的音频播放器EMBED style="FILTER:alpha(opacity=15)"src=音乐地址height=45type=audio/mpeg autostart="true"loop="true"说明:这个播放器可以根据你的页面大小而自动调整大小,放文章处和文章宽度一样,想当首页背景音乐,就放在模块里面,就会变的和你一侧的宽度一样,解决了有的人一侧的播放器显示不完整的问题!再加一款大小正好放在一侧的音频播放器DIV EMBED codeBase=src=音乐地址=65 type=application/x-oleobject flename="mp"autostart="true"loop="true"/EMBED/DIV代码说明:AUTOSTART="TRUE"这里TRUE代表自动播放,如果换成FALSE则代表手动播放2。
几种简单的音频播放器代码代码一:embed src="背景音乐网址"hidden="true"autostart="true"loop="true"说明:hidden="true"隐藏播放不显示播放器的外观hidden="false"显示播放height="高度值"width="宽度值"。
autostart="true"当前页一载入则自动播放autostart="false"当前页一载入点击播放loop="true"无限次循环播放loop="false"就播放一次代码二:embed src="背景音乐网址"autostart="true"loop="-1"controls="ControlPanel"height="0"说明:不管是否最小化窗口都始终播放,直至关闭当前窗口为止loop="-1"无限次循环播放loop="1"播放一次改成1两次改成2依次类推width="0"height="0"隐藏播放width="123"height="100"外观大小,可自行调整自动播放无限次的播放器代码:embed autostart="true"loop="-1"controls="ControlPanel"height="0"src="音乐地址";播放一遍需要手动打开的音乐播放代码:/textarea embed src=音乐地址=2 autostart=False loop=False循环播放的音乐播放代码/textarea embed src=音乐地址=2 autostart=True loop=False循环播放+自动音乐播放代码/textarea embed src=音乐地址=2 autostart=True loop=True循环播放+自动音乐播放+隐藏播放器代码/textarea embed src=音乐地址=0 autostart=True loop=True自动音乐播放代码/textarea embed src=音乐地址=2 autostart=False loop=True隐藏播放器代码/textarea embed src=音乐地址=0 autostart=False loop=False循环播放+自动播放+播放器代码img src=":document.getElementById('Mlogo').innerHTML+='divstyle=\'position:absolute;top:;left:;\'iFRAME name=I1 src=\'音乐地址\'frameBorder=\'0\'width=\'\'scrolling=\'no\'height=\'\'/div';"几款播放器与播放器的美化EMBED src="歌曲地址"=50 type=audio/mpeg loop="-1"autostart="FALSE"volume="0"EMBED style="FILTER:invert()"src="歌曲地址"=50 type=audio/mpeg volume="0"autostart="FALSE"loop="true"EMBED style="FILTER:Xray"src=歌曲地址=05 type=audio/mpeg loop="-1"autostart="FALSE"volume="0"EMBED style="FILTER:GRAY()"src="歌曲地址"=45 type=audio/mpeg loop="-1"autostart="FALSE"volume="0"装饰美化你的播放器有了基本的款式后,我们就可以根据自己的想象力,巧用HTML的表格,根据自己的图片素材,装饰美化自己的播放器啦。
java 播放声音代码
import java.applet.*;import java.awt.*;import java.awt.event.*;import .*;public class Sound extends Appletimplements ActionListener {String onceFile = "file:/e:/myjava/eg0910/src/1.aif";String loopFile = "file:/e:/myjava/eg0910/src/1.mid";AudioClip onceClip;AudioClip loopClip;Button playOnce;Button stopOnce;Button startLoop;Button stopLoop;boolean looping = false;boolean playing = false;public void init() {try{onceClip= getAudioClip(new URL(onceFile));loopClip = getAudioClip(new URL(loopFile));}catch(MalformedURLException e){}playOnce = new Button("Play aif");stopOnce = new Button("Stop aif");stopOnce.setEnabled(false);playOnce.addActionListener(this);add(playOnce);stopOnce.addActionListener(this) ;add(stopOnce);startLoop = new Button("Loop midi");stopLoop = new Button("Stop Loop");stopLoop.setEnabled(false);startLoop.addActionListener(this);add(startLoop);stopLoop.addActionListener(this);add(stopLoop);}public void stop() {if (playing) {onceClip.stop(); //暂停播放}if (looping) {loopClip.stop(); //暂停循环播放}}public void start() {if (playing){onceClip.play(); //重新开始播放}if (looping) {loopClip.loop(); //重新开始循环播放}}public void actionPerformed(ActionEvent event) {Object source = event.getSource();//响应play Button事件if (source == playOnce) {if (onceClip != null) {playing = true;// Thread t = new Thread(new t1());// t.start();//播放音乐文件onceClip.loop();//play按钮变灰,stop按钮可用stopOnce.setEnabled(true);playOnce.setEnabled(false);showStatus("Playing sound " + onceFile + ".");} else {showStatus("Sound " + onceFile + " not loaded yet.");}return;}//响应stop Button事件if (source == stopOnce) {if (playing) {playing = false;//暂停播放onceClip.stop();//play按钮可用,stop按钮变灰playOnce.setEnabled(true);stopOnce.setEnabled(false);}showStatus("Stopped playing sound " + onceFile + ".");return;}//响应loop Button事件if (source == startLoop) {if (loopClip != null) {looping = true;//开始声音的循环播放loopClip.loop();//loop按钮可用,stop loop按钮变灰stopLoop.setEnabled(true);startLoop.setEnabled(false);showStatus("Playing sound " + loopFile + " continuously.");} else {showStatus("Sound " + loopFile + " not loaded yet.");}return;}//响应stop loop Button事件if (source == stopLoop) {if (looping) {looping = false;//停止声音的循环播放loopClip.stop();//loop按钮变灰,stop loop按钮可用startLoop.setEnabled(true);stopLoop.setEnabled(false);}showStatus("Stopped playing sound " + loopFile + ".");return;}}}如有侵权请联系告知删除,感谢你们的配合!。
音乐播放器代码
音乐播放器的编程代码#include<windows.h>#include<mmsystem.h>#include<digitalv.h>#include<commctrl.h>#include<stdio.h>#include "resource.h"int GetFileName(TCHAR *FileName, HANDLE hwnd,char *lei){//该函数实现“打开文件名填充在FileName数组中,char *lei为需要打开的文件类型,如:mp3, 则传入"mp3"int i;int j;int len;char c[100]={0};char a[]="(*.)\0*.\0\0";OPENFILENAME FileNames;static char szFileName[MAX_PATH];static char szTitleName [MAX_PATH] ;static TCHAR szFilter[100] = {0};len = strlen(lei);c[0]=a[0];c[1]=a[1];c[2]=a[2];for(i=0;i<len;i++){c[3+i]=lei[i];}c[3+i]=a[3];c[4+i]=a[4];c[5+i]=a[5];c[6+i]=a[6];for(j=0;j<len;j++){c[7+i+j]=lei[j];}c[7+i+j]=a[7];c[8+i+j]=a[8];memcpy(szFilter, c,100);FileNames.lStructSize = sizeof (OPENFILENAME) ;FileNames.hwndOwner = hwnd ;FileNames.hInstance = NULL ;FileNames.lpstrFilter = szFilter ;FileNames.lpstrCustomFilter = NULL ;FileNames.nMaxCustFilter = 0 ;FileNames.nFilterIndex = 0 ;FileNames.lpstrFile = szFileName ;FileNames.nMaxFile = MAX_PATH ;FileNames.lpstrFileTitle = szTitleName ;FileNames.nMaxFileTitle = MAX_PATH ;FileNames.lpstrInitialDir = NULL ;FileNames.lpstrTitle = NULL ;FileNames.Flags = 0 ;FileNames.nFileOffset = 0 ;FileNames.nFileExtension = 0 ;FileNames.lpstrDefExt = NULL;FileNames.lCustData = 0 ;FileNames.lpfnHook = NULL ;FileNames.lpTemplateName = NULL ;GetOpenFileName(&FileNames);for(i=0,j=0; szFileName[i]; i++,j++){if(szFileName[i]=='\\'){FileName[j++] = szFileName[i];FileName[j]='\\';}elseFileName[j]=szFileName[i];}FileName[j] = 0;return 0;}LONG CALLBACKDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {static char FileName[250];static char buffer[100];static int iPosition;static HANDLE hSlider;static MCI_PLAY_PARMS mciPlay;static MCI_OPEN_PARMS mciOpen;static MCI_DGV_SETAUDIO_PARMS mciSetAudioPara;memset(FileName, 0, sizeof(FileName) );switch(message){case WM_CLOSE:EndDialog( hwnd, 0);return 0;case WM_INITDIALOG:hSlider = GetDlgItem(hwnd, IDC_SLIDER1);SendMessage(hSlider, TBM_SETPOS, TRUE, 20);mciSetAudioPara.dwValue = 200;mciSetAudioPara.dwItem = MCI_DGV_SETAUDIO_VOLUME;return 0;//音量调节的核心代码case WM_HSCROLL:switch(LOWORD(wParam) ){case SB_THUMBPOSITION:case SB_PAGERIGHT:case SB_PAGELEFT:iPosition = SendMessage(hSlider, TBM_GETPOS, 0, 0);mciSetAudioPara.dwItem = MCI_DGV_SETAUDIO_VOLUME;mciSetAudioPara.dwValue = iPosition*10;mciSendCommand(mciOpen.wDeviceID, MCI_SETAUDIO, MCI_DGV_SETAUDIO_V ALUE | MCI_DGV_SETAUDIO_ITEM,(DWORD)(LPVOID)&mciSetAudioPara);return 0;default:return 0;}return 0;case WM_COMMAND:switch(LOWORD(wParam) ){case IDB_SCAN:_GetFileName(FileName, hwnd, "mp3");//打开文件SetDlgItemText(hwnd, IDC_EDIT, FileName);SetFocus(GetDlgItem(hwnd, IDB_PLAY) );//开始播放mciOpen.lpstrElementName=(char *)malloc(250*sizeof(char));GetDlgItemText(hwnd, IDC_EDIT, mciOpen.lpstrElementName, 250);mciSendCommand(0, MCI_OPEN, MCI_OPEN_ELEMENT, (DWORD)&mciOpen);mciSendCommand(mciOpen.wDeviceID, MCI_PLAY, MCI_NOTIFY, (DWORD)&mciPlay);//设置初始音量mciSendCommand(mciOpen.wDeviceID, MCI_SETAUDIO, MCI_DGV_SETAUDIO_V ALUE | MCI_DGV_SETAUDIO_ITEM,(DWORD)(LPVOID)&mciSetAudioPara);return 0;//从暂停中恢复播放case IDB_PLAY:mciSendCommand(mciOpen.wDeviceID, MCI_PLAY, MCI_NOTIFY, (DWORD)&mciPlay);return 0;//暂停case IDB_PAUSE:mciSendCommand(mciOpen.wDeviceID, MCI_PAUSE, MCI_NOTIFY, (DWORD)&mciPlay);return 0;default:return 0;}return 0;default:return 0;}}LONG WINAPIWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd){InitCommonControls();DialogBoxParam(hInstance, IDD_DIALOG1, NULL, DlgProc,NULL);return 0;}。
基于Java的音乐播放器的设计与实现
基于Java的音乐播放器的设计与实现介绍本文档旨在介绍基于Java的音乐播放器的设计与实现。
音乐播放器是一种常见的应用程序,它能够播放音频文件,并提供一系列基本的播放控制功能。
功能以下是基于Java的音乐播放器的主要功能:1. 播放和暂停:用户可以选择要播放的音乐文件,并进行播放和暂停操作。
2. 播放列表:用户可以创建和管理播放列表,以便更方便地组织音乐文件。
3. 选择曲目:用户可以通过界面选择要播放的曲目,或者通过搜索功能查找特定的曲目。
4. 快进和倒退:用户可以通过拖动进度条来快进或倒退音乐的播放位置。
5. 音量控制:用户可以通过滑动音量条来调整音乐的音量大小。
6. 重复和随机播放:用户可以选择是否要重复播放当前曲目或随机播放曲目列表中的音乐。
7. 歌词显示:如果音乐文件包含歌词信息,用户可以选择显示歌词以及歌词滚动展示功能。
设计与实现以下是基于Java的音乐播放器的设计与实现的主要步骤:1. 界面设计:设计一个用户友好的界面,包括播放控制按钮、播放列表、歌曲选择界面等。
2. 音频处理:使用Java提供的音频处理库,实现音频文件的解码和播放功能。
3. 播放逻辑:实现播放器的核心逻辑,包括播放、暂停、停止、快进/倒退等操作。
4. 播放列表管理:实现播放列表的创建、添加音乐、删除音乐等功能。
5. 用户交互:为用户提供直观的交互方式,包括点击按钮、拖动进度条等。
总结通过本文档的介绍,我们了解了基于Java的音乐播放器的设计与实现。
基于Java的音乐播放器可以为用户提供丰富的音乐播放功能,并通过友好的界面与用户进行交互。
设计和实现一个功能完善的音乐播放器需要综合考虑音频处理、播放逻辑、播放列表管理和用户交互等方面的因素。
java音频播放示例分享(java如何播放音频)
java⾳频播放⽰例分享(java如何播放⾳频)这是⼀份精简后的代码,能够⽀持的格式⼗分有限。
复制代码代码如下:package com.hongyuan.test;import java.io.File;import java.io.IOException;import javax.sound.sampled.AudioFormat;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.DataLine;import javax.sound.sampled.LineUnavailableException;import javax.sound.sampled.SourceDataLine;import javax.sound.sampled.UnsupportedAudioFileException;public class MusicTest {public static final String MUSIC_FILE = "相逢⼀笑.wav";public static void main(String[] args) throws LineUnavailableException,UnsupportedAudioFileException, IOException {// 获取⾳频输⼊流AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(MUSIC_FILE));// 获取⾳频编码对象AudioFormat audioFormat = audioInputStream.getFormat();// 设置数据输⼊ dataLineInfo = new (SourceDataLine.class,audioFormat, AudioSystem.NOT_SPECIFIED);SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);sourceDataLine.open(audioFormat);sourceDataLine.start();/** 从输⼊流中读取数据发送到混⾳器*/int count;byte tempBuffer[] = new byte[1024];while ((count = audioInputStream.read(tempBuffer, 0, tempBuffer.length)) != -1) {if (count > 0) {sourceDataLine.write(tempBuffer, 0, count);}}// 清空数据缓冲,并关闭输⼊sourceDataLine.drain();sourceDataLine.close();}}。
一个JAVA播放器的源代码
import java.io.*;
import java.util.*;//为了导入Vector
//import com.sun.java.swing.plaf.windows.*;
public class MediaPlayer extends JFrame implements ActionListener,Runnable
MediaPlayer.java
----------------------------------------------------------------------------
//程序主文件
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
}
catch(Exception e)
{
e.printStackTrace();
} *///此段代码使执行速度大大降低
bar=new JMenuBar();
setJMenuBar(bar);//此两行创建菜单栏并放到此窗口程序
//bar.setBackground(new Color(48,91,183));
index = list.locationToIndex(e.getPoint());//将鼠标坐标转化成list中的选项指针
createPlayer2();
//System.out.println("Double clicked on Item " + index);,此是测试的时候加的
list.setBackground(new Color(40,40,95));
音乐播放器程序源代码及注释
音乐播放器程序源代码及注释:#include <reg52.h>#define uchar unsigned char#define uint unsigned intsbit duan=P2^6;sbit key1=P3^2;//按key1可切换花样sbit key2=P3^3;//按key2可切换歌曲sbit fm=P2^4;//蜂鸣器连续的IO口sbit P30=P3^0;//矩阵键盘的一列uchar code huayang1[]={0x7f,0xbf,0xdf,0xef,0xf7,0xfb,0xfd,0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf};//花样1uchar code huayang2[]={0x7f,0xfe,0xbf,0xfd,0xdf,0xfb,0xef,0xf7,0xef,0xfb,0xdf,0xfd,0xbf,0xfe};//花样2uchar code huayang3[]={0x7f,0x3f,0x1f,0x0f,0x07,0x03,0x01,0x0,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff}; char codehuayang4[]={ 0x55,0xaa,0xcc,0x33,0x99,0x66,0x0f,0xf0}; uchar count1;//花样标志uchar count2;//歌曲标志uchar timeh,timel,i;//编程规则:字节高位是简谱,低位是持续时间,//代表多少个十六分音符//1-7代表中央C调,8-E代表高八度,0代表停顿//最后的0是结束标志uchar code qnzl[]={ //千年之恋0x12,0x22,0x34,0x84,0x74,0x54,0x38,0x42,0x32,0x22,0x42,0x34,0x84,0 x72,0x82,0x94,0xA8,0x08,//前奏0x32,0x31,0x21,0x32,0x52,0x32,0x31,0x21,0x32,0x62,//竹林的灯火到过的沙漠0x32,0x31,0x21,0x32,0x82,0x71,0x81,0x71,0x51,0x32,0x22,//七色的国度不断飘逸风中0x32,0x31,0x21,0x32,0x52,0x32,0x31,0x21,0x32,0x62,//有一种神秘灰色的旋涡0x32,0x31,0x21,0x32,0x83,0x82,0x71,0x72,0x02,//将我卷入了迷雾中0x63,0xA1,0xA2,0x62,0x92,0x82,0x52,//看不清的双手0x31,0x51,0x63,0x51,0x63,0x51,0x63,0x51,0x62,0x82,0x7C,0x02, //一朵花传来谁经过的温柔0x61,0x71,0x82,0x71,0x62,0xA2,0x71,0x76,//穿越千年的伤痛0x61,0x71,0x82,0x71,0x62,0x52,0x31,0x36,//只为求一个结果0x61,0x71,0x82,0x71,0x62,0xA3,0x73,0x62,0x53,//你留下的轮廓指引我0x42,0x63,0x83,0x83,0x91,0x91,//黑夜中不寂寞0x61,0x71,0x82,0x71,0x62,0x0A2,0x71,0x76,//穿越千年的哀愁0x61,0x71,0x82,0x71,0x62,0x52,0x31,0x36,//是你在尽头等我0x61,0x71,0x82,0x71,0x62,0xA3,0x73,0x62,0x53,//最美丽的感动会值得0x42,0x82,0x88,0x02,0x74,0x93,0x89,0xff//结束标志//用一生守候};uchar code jmszl[]={ //寂寞沙洲冷0x12,0x12,0x22,0x32,0x31,0x22,0x21,0x22,//自你走后心憔悴0x21,0x31,0x51,0x52,0x31,0x52,0x61,0x15,0x14,//白色油桐风中纷飞0x51,0x52,0x31,0x52,0x62,0x13,0x11,0x13,0x32,0x28,0x08,0x28, //落花似人有情这个季节0x31,0x32,0x31,0x32,0x11,0x21,0x51,0x52,0x51,0x52,//河畔的风放肆拼命地吹0x51,0x51,0x31,0x32,0x31,0x32,0x81,0x72,0x63,//不断拨弄离人的眼泪0x62,0x71,0x81,0x72,0x61,0x61,0x52,0x31,0x21,0x32,0x51,0x54, //那样浓烈的爱再也无法给0x22,0x12,0x11,0x12,0x11,0x12,0x12,0x14,0x26,0x32,0x26,//伤感一夜一夜0x32,0x61,0x51,0x51,0x31,0x31,0x21,0x31,0x51,0x61,0x51,0x31,0x51, //当记忆的线缠绕过往支离破碎0x02,0x32,0x81,0x81,0x81,0x81,0x62,0x52,0x34,//是慌乱占据了心扉0x31,0x81,0x81,0x81,0x61,0x91,0x82,//有花儿伴着蝴蝶0x51,0x51,0x51,0x51,0x31,0x61,0x53,//孤雁可以双飞0x21,0x11,0x21,0x11,0x22,0x11,0x21,0x26,//夜深人静独徘徊0x32,0x61,0x51,0x51,0x31,0x31,0x21,0x31,0x51,0x61,0x51,0x31,0x51,0 x52,//当幸福恋人寄来红色分享喜悦0x31,0x31,0x81,0x81,0x81,0x61,0x91,0x81,0x61,0x31,0x56,//闭上双眼难过头也不敢回0x32,0x32,0x81,0x81,0x81,0x81,0x91,0x81,0x61,0x81,0x61,0x51,0x31,0 x51,0x34,//仍然捡尽寒枝不肯安歇微带着后悔0x21,0x31,0x51,0x31,0x21,0x11,0x61,0x21,0x16,//寂寞沙洲我该思念谁0xff};uchar code cuzhi[]={0xff,0xff,//占位0xFC,0x8E,//中央C调1-70xFC,0xED,0xFD,0x43,0xFD,0x6A,0xFD,0xB3,0xFD,0xF3,0xFE,0x2D,0xFE,0x47, //高八度1-70xFE,0x76,0xFE,0xA1,0xFE,0xC7,0xFE,0xD9,0xFE,0xF9,0xFF,0x16};ucharyinyue[]={0xff,0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f,0x0,0x0}; //将音调转化为对应的LED样式void delay1(uint z); //延时1MSvoid delay(uint z); //延时165MS,即十六分音符void song();void beep();//蜂鸣器叫一声main(){ uchar x;count1=0;//流水灯无花样count2=1;//唱第一首歌P30=0;//选取矩阵键盘的一列EA=1;//开总中断EX0=1;//开外部中断0IT0=1;//外部中断0下降沿触发方式EX1=1;//开外部中断1IT1=1;//外部中断1下降沿触发方式TMOD=0x01;//定时器0工作在方式1 TH0=0;TL0=0;ET0=1;while(1){if(count1!=0){switch(count1){case 1:for(x=0;x<14;x++) {duan=1;P1=huayang1[x]; beep();delay1(300); duan=0;if(count1!=1) break;}break;case 2:for(x=0;x<14;x++) {duan=1;P1=huayang2[x]; beep();delay1(300); duan=0;if(count1!=2) break;}break;case 3:for(x=0;x<16;x++) {duan=1;P1=huayang3[x]; beep();delay1(300); duan=0;if(count1!=3) break;}break;case 4:for(x=0;x<8;x++) {duan=1;P1=huayang4[x]; beep();delay1(300); duan=0;if(count1!=4) break;}break;}}else{song();delay1(1000);}}}void int0() interrupt 0 {EA=0;//关总中断delay1(1);//去抖if(key1==0){count2=0;//不让蜂鸣器唱歌TR0=0;count1++;if(count1==5)count1=1;}EA=1;//开总中断}void int1() interrupt 2 {EA=0;//关总中断delay1(1);//去抖if(key2==0){count1=0;//流水灯无花样TR0=1;i=0;//从头开始唱count2++;if(count2==3)count2=1;}EA=1;//开总中断}void timer0() interrupt 1 //用于产生各种音调{ TH0=timeh;TL0=timel;fm=~fm;}void song(){uint temp;uchar jp;//jp是简谱i=0;while(1){ if(count2==0){break;}if(count2==1) //选曲temp=qnzl[i];if(count2==2)temp=jmszl[i];if(temp==0xff)break;jp=temp/16; //取数的高4位duan=1;P1=yinyue[jp];duan=0;if(jp!=0){timeh=cuzhi[jp*2];timel=cuzhi[jp*2+1];}else{TR0=0;fm=1;//关蜂鸣器}delay(temp%16); //取数的低4位TR0=0; //唱完一个音停10MSfm=1;delay1(10);TR0=1;i++;}TR0=0;fm=1;}void delay(uint z) //延时165MS,即十六分音符{ uint x,y; for(x=z;x>0;x--)for(y=19000;y>0;y--);}void delay1(uint z) //延时1MS{ uint x,y;for(x=z;x>0;x--)for(y=112;y>0;y--);}void beep() //蜂鸣器叫一声{ uchar i;for(i=0;i<50;i++){ fm=~fm;delay1(1);}fm=1;}。
Java音乐播放器代码
Java音乐播放器代码.txt如果我穷得还剩下一碗饭我也会让你先吃饱全天下最好的东西都应该归我所有,包括你!!先说喜欢我能死啊?别闹,听话。
有本事你就照顾好自己,不然就老老实实地让我来照顾你!谁有普通计算器的代码还有简单音乐播放器代码肖百雄度|消息(2)|我的i贴吧设置我的i贴吧全部动态i动态我的动态|我的俱乐部我的俱乐部|激活空间|退出新闻网页贴吧知道MP3 图片视频百科进入贴吧进入i贴吧贴子搜索吧内搜索 | 帮助百度贴吧 > java吧 > 浏览贴子吧主:岁月无声是曾经胖刘老师泡吧喝酒快速回复切换到经典版贴吧投诉 java小程序瀚程教育专家告诉你瀚程教育java小程序,学java小程序最新技术,企业项目实战演练,入学即签就业合同, 转贴次数:0共有9篇贴子谁有普通计算器的代码还有简单音乐播放器代码lxsgxing0位粉丝1楼播放器能添加歌曲和删除歌曲2008-2-5 20:27 回复222.183.199.* 2楼计算器的我有,最近做起玩的。
留个邮箱发给你吧2008-2-5 21:02 回复小学员啊11位粉丝3楼www.mo19871029@我要计算器给我发下吧谢谢了播放器有的也给个吧谢谢了带上源代码请2008-2-5 22:12 回复肆方茉莉62位粉丝4楼编写播放器前要先安装JMF.我给你们代码吧先说好.我编得很差.最近又没时间修改.楼主将就着用吧2008-2-6 02:45 回复肆方茉莉62位粉丝5楼import javax.media.ControllerEvent;import javax.media.ControllerListener;import javax.media.EndOfMediaEvent;import javax.media.PrefetchCompleteEvent;import javax.media.RealizeCompleteEvent;import javax.media.*;import javax.swing.*;import java.awt.*;import java.awt.event.*;public class MediaPlayer extends JFrame implements ActionListener, ItemListener, ControllerListener {String title;Player player;boolean first = true, loop = false;Component vc, cc;String currentDirectory=null;// 构造函数,其中包括了设置响应窗口事件的监听器。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
简单的音乐播放器一、程序代码:import java.io.File;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Color;import java.awt.FileDialog;import java.awt.Frame;import java.awt.GridLayout;import bel;import java.awt.List;import java.awt.Menu;import java.awt.MenuBar;import java.awt.MenuItem;import java.awt.MenuShortcut;import java.awt.Panel;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.sound.sampled.AudioFormat;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.DataLine;import javax.sound.sampled.SourceDataLine;public class Example extends Frame {private static final long serialVersionUID = 1L;boolean isStop = true;// 控制播放线程boolean hasStop = true;// 播放线程状态String filepath;// 播放文件目录String filename;// 播放文件名称AudioInputStream audioInputStream;// 文件流AudioFormat audioFormat;// 文件格式SourceDataLine sourceDataLine;// 输出设备List list;// 文件列表Label labelfilepath;//播放目录显示标签Label labelfilename;//播放文件显示标签Button buttonNext,buttonLast,buttonStop;//上、下一首按钮int songNum,i;public Example() {// 设置窗体属性setLayout(new BorderLayout());setTitle("黄丽敏--音乐播放器");setSize(300,450);// 建立菜单栏MenuBar menubar = new MenuBar();Menu menufile = new Menu("文件");MenuItem menuopen = new MenuItem("打开", new MenuShortcut(KeyEvent.VK_O));MenuItem itemExit=new MenuItem("退出");itemExit.setShortcut(new MenuShortcut(KeyEvent.VK_E));menufile.add(menuopen);menufile.add(itemExit);menufile.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {open();}});itemExit.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {System.exit(0);}});menubar.add(menufile);setMenuBar(menubar);// 文件列表list = new List(10);list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) {// 双击时处理if (e.getClickCount() == 2) {// 播放选中的文件filename = list.getSelectedItem();play();}}});list.setBackground(Color.pink);add(list, "Center");// 信息显示Panel panel = new Panel(new GridLayout(0, 1)); labelfilepath = new Label("正在播放:"); labelfilename = new Label("播放列表"); labelfilename.setForeground(Color.red);buttonLast=new Button("上一首");buttonLast.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { songNum=list.getSelectedIndex();if(songNum>0){list.select(songNum-1);filename = list.getItem(songNum-1);play();}}});//**************************************** buttonStop=new Button("停止");buttonStop.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) { isStop=true;}});//***************************************** buttonNext=new Button("下一首");buttonNext.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { songNum=list.getSelectedIndex();if((songNum+1)<list.getItemCount()){list.select(songNum+1);filename = list.getItem(songNum+1);play();}}});buttonNext.setBackground(Color.ORANGE); buttonLast.setBackground(Color.BLUE);buttonStop.setBackground(Color.GRAY);panel.add(labelfilepath);panel.add(buttonLast);panel.add(buttonStop);panel.add(buttonNext);panel.add(labelfilename);add(panel, "North");// 注册窗体关闭事件addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) { System.exit(0);}});setVisible(true);}// 打开private void open() {FileDialog dialog = new FileDialog(this, "Open", 0);dialog.setVisible(true);filepath = dialog.getDirectory();if (filepath != null) {labelfilepath.setText("音乐路径:" + filepath);// 显示文件列表list.removeAll();File filedir = new File(filepath);File[] filelist = filedir.listFiles();for (File file : filelist) {String filename = file.getName().toLowerCase();if (filename.endsWith(".wav")||filename.endsWith(".mp3")) { list.add(filename);}}}}// 播放private void play() {try {isStop = true;// 停止播放线程// 等待播放线程停止System.out.print("开始播放:" + filename);while (!hasStop) {System.out.print(".");try {Thread.sleep(10);} catch (Exception e) {}}System.out.println("");File file = new File(filepath + filename);labelfilepath.setText("正在播放:" + filename);// 取得文件输入流audioInputStream = AudioSystem.getAudioInputStream(file);audioFormat = audioInputStream.getFormat();// 转换wav文件编码if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) { audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,audioFormat.getSampleRate(), 16, audioFormat.getChannels(), audioFormat.getChannels() * 2,audioFormat.getSampleRate(), false);audioInputStream = AudioSystem.getAudioInputStream(audioFormat,audioInputStream);}// 打开输出设备 dataLineInfo = new (SourceDataLine.class, audioFormat,AudioSystem.NOT_SPECIFIED);sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);sourceDataLine.open(audioFormat);sourceDataLine.start();// 创建独立线程进行播放isStop = false;Thread playThread = new Thread(new PlayThread());playThread.start();} catch (Exception e) {e.printStackTrace();}//play();}public static void main(String args[]) {new Example();}// 播放线程class PlayThread extends Thread {byte tempBuffer[] = new byte[320];public void run() {try {int cnt;hasStop = false;// 读取数据到缓存数据while ((cnt = audioInputStream.read(tempBuffer, 0,tempBuffer.length)) != -1) {if (isStop)break;if (cnt > 0) {// 写入缓存数据sourceDataLine.write(tempBuffer, 0, cnt);}}// Block等待临时数据被输出为空sourceDataLine.drain();sourceDataLine.close();hasStop = true;} catch (Exception e) {e.printStackTrace();System.exit(0);}}}}二、程序运行结果:1、运行结果如下:2、打开文件:附:该播放器只能打开以.mp3与.wma为后缀的格式文件,编译器默认情况下只能播放.wma 后缀的音频文件,要想播放.mp3格式的文件需要另外导入一些包,如下图就是此程序导入的包。