/** Signals that a PooledThread has stopped. Drains and closes the Thread's Line. */ protected void threadStopped() { SourceDataLine line = (SourceDataLine) localLine.get(); if (line != null) { line.drain(); line.close(); } }
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(); } }
// 播放au,aiff,wav音乐流, 这个函数基本完全为帖子上的代码 private synchronized void play() { ByteArrayInputStream aMusicInputStream; AudioFormat format; AudioInputStream musicInputStream; byte[] audioSamples; SourceDataLine line; try { File MusicFile = new File(m_filename); musicInputStream = AudioSystem.getAudioInputStream(MusicFile); // 取得文件的音频输入流 format = musicInputStream.getFormat(); // 取得音频输入流的格式 audioSamples = getAudioSamples(musicInputStream, format); // 取得音频样本 aMusicInputStream = new ByteArrayInputStream(audioSamples); int bufferSize = format.getFrameSize() * Math.round(format.getSampleRate() / 10); byte[] buffer = new byte[bufferSize]; try { DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format, bufferSize); } catch (LineUnavailableException e) { e.printStackTrace(); return; } if (!line.isRunning()) { line.start(); } int numBytesRead = 0; while (numBytesRead != -1 && !m_stopped) { numBytesRead = aMusicInputStream.read(buffer, 0, buffer.length); if (numBytesRead != -1) { line.write(buffer, 0, numBytesRead); } } line.drain(); line.close(); } catch (Exception e) { e.printStackTrace(); } }
/** Close standard audio. */ public static void close() { line.drain(); line.stop(); }