标签:
MusicPlayer.javapackage musicplayer; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.WindowConstants; /** * * @author Chandler */ public class MusicPlayer extends JFrame{ private Container container; private JButton playbutton; private PlayBackThread playbackthread; //默认构造函数 public MusicPlayer(String title){ super(title); container = this.getContentPane(); playbutton = new JButton("播放"); playbutton.setSize(50,20); playbutton.addActionListener(new PlayActionListener()); this.setLayout(new BorderLayout()); this.setSize(500,400); container.add(playbutton,BorderLayout.CENTER); Toolkit toolkit = Toolkit.getDefaultToolkit(); int x = (int)(toolkit.getScreenSize().getWidth()-this.getWidth())/2; int y = (int)(toolkit.getScreenSize().getHeight()-this.getHeight())/2; this.setLocation(x,y); this.setVisible(true); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here MusicPlayer musicplayer = new MusicPlayer("MusicPlayer"); } class PlayActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); playbackthread = new PlayBackThread(); playbackthread.start(); } } }
PlayBackThread.java
package musicplayer; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.LineUnavailableException; import java.io.RandomAccessFile; import java.util.Scanner; /** * * @author Chandler */ public class PlayBackThread extends Thread{ private SourceDataLine dataline; private final int dataOffset = 0x2e; public PlayBackThread(){ super("playbackthread"); } @Override public void run(){ try{ RandomAccessFile raf = new RandomAccessFile("C:\\Users\\Chandler\\Documents\\NetBeansProjects\\MusicPlayer\\src\\musicplayer\\John Denver - Country Roads.wav","r"); AudioFormat af; af = new AudioFormat(44100,16,2,true,false); dataline = (SourceDataLine)AudioSystem.getSourceDataLine(af); dataline.open(af); raf.seek(dataOffset); int hasRead=0; dataline.start(); byte[] buff=new byte[4096]; Scanner input = new Scanner(System.in); while((hasRead=raf.read(buff))>0){ // print(raf.getFilePointer(),buff); dataline.write(buff, 0, hasRead); } dataline.stop(); } catch(Exception e){ e.printStackTrace(); } } public static void print(long pointer, byte[] buff){ System.out.format("%x: " ,pointer); System.out.format("%x ", buff[0]); System.out.format("%x ", buff[1]); System.out.format("%x ", buff[2]); System.out.format("%x ", buff[3]); System.out.println(); } }
John Denver - Country Roads.wav
标签:
原文地址:http://blog.csdn.net/u010760567/article/details/51335341