public void run() { try { AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile); AudioFormat format = ais.getFormat(); // System.out.println("Format: " + format); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info); source.open(format); source.start(); int read = 0; byte[] audioData = new byte[16384]; while (read > -1) { read = ais.read(audioData, 0, audioData.length); if (read >= 0) { source.write(audioData, 0, read); } } donePlaying = true; source.drain(); source.close(); } catch (Exception exc) { System.out.println("error: " + exc.getMessage()); exc.printStackTrace(); } }
public static Clip loadClip(URL url) { Clip clip = null; String fnm = "" + url; try { AudioInputStream stream = AudioSystem.getAudioInputStream(url); AudioFormat format = stream.getFormat(); if ((format.getEncoding() == AudioFormat.Encoding.ULAW) || (format.getEncoding() == AudioFormat.Encoding.ALAW)) { AudioFormat newFormat = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), format.getSampleSizeInBits() * 2, format.getChannels(), format.getFrameSize() * 2, format.getFrameRate(), true); // big endian stream = AudioSystem.getAudioInputStream(newFormat, stream); // System.out.println("Converted Audio format: " + newFormat); format = newFormat; } DataLine.Info info = new DataLine.Info(Clip.class, format); // make sure sound system supports data line if (!AudioSystem.isLineSupported(info)) { System.out.println("Unsupported Clip File: " + fnm); return null; } // get clip line resource clip = (Clip) AudioSystem.getLine(info); clip.open(stream); // open the sound file as a clip stream.close(); // we're done with the input stream // duration (in secs) of the clip double duration = clip.getMicrosecondLength() / 1000000.0; // new if (duration <= 1.0) { System.out.println("WARNING. Duration <= 1 sec : " + duration + " secs"); System.out.println( " The clip in " + fnm + " may not play in J2SE 1.5 -- make it longer"); } // else // System.out.println(fnm + ": Duration: " + duration + " secs"); } // end of try block catch (UnsupportedAudioFileException audioException) { System.out.println("Unsupported audio file: " + fnm); } catch (LineUnavailableException noLineException) { System.out.println("No audio line available for : " + fnm); } catch (IOException ioException) { System.out.println("Could not read: " + fnm); } catch (Exception e) { System.out.println("Problem with " + fnm); } return clip; } // end of loadClip()