Musicplayer.java
Package 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; Default constructor public Musicplayer (String title) {Super (title); container = This.getcontentpane (); PlayButton = new JButton ("Play"); 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) {//TOD O 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\\cha Ndler\\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
How to write a native WAV player in Java