The JavaSoundUser class is just a test class to create instances of the JavaSoundPlayer class.
JavaSoundPlayer.java |
1 package example; 2 3 import java.net.*; 4 import java.io.File; 5 import javax.media.*; 6 import javax.sound.midi.*; 7 import javax.sound.sampled.*; 8 9 public class JavaSoundPlayer { 10 11 private String filename; 12 private File file; 13 private AudioInputStream ais; 14 private Clip clip; 15 private boolean iswav; 16 private boolean ismidi; 17 private boolean ismp3; 18 private Sequence seq; 19 private Sequencer mp; 20 private Player player; 21 22 public JavaSoundPlayer(String filename) { 23 this.filename = filename; 24 iswav = ismidi = ismp3 = false; 25 if (filename.endsWith("wav") 26 || filename.endsWith("au") 27 || filename.endsWith("aiff")) { 28 iswav = true; 29 // from a sampled wave File 30 try { 31 file = new File(filename); 32 ais = AudioSystem.getAudioInputStream(file); 33 clip = AudioSystem.getClip(); 34 // pre-load samples from the AudioInputStream 35 clip.open(ais); 36 } catch (Exception e) { 37 } 38 } else if (filename.endsWith("mid")) { 39 ismidi = true; 40 try { 41 file = new File(filename); 42 seq = MidiSystem.getSequence(file); 43 mp = MidiSystem.getSequencer(); 44 mp.open(); 45 mp.setSequence(seq); 46 mp.setLoopCount(0); // repeat 0 times 47 } catch (Exception e) { 48 } 49 } else if (filename.endsWith("mp3")) { 50 ismp3 = true; 51 try { 52 player = Manager.createPlayer( 53 new URL("file:"+filename)); 54 player.realize(); 55 } catch (Exception e) { 56 } 57 } 58 } 59 60 public void play() { 61 if (iswav) { 62 if (clip.isRunning()) { 63 clip.stop(); 64 } 65 // rewind to beginning and play 66 clip.setFramePosition(0); 67 clip.start(); 68 } else if (ismidi) { 69 if (mp.isRunning()) { 70 mp.stop(); 71 } 72 mp.setTickPosition(0); 73 mp.start(); 74 } else if (ismp3) { 75 player.start(); 76 } 77 } 78 } 79
No comments:
Post a Comment