public void run() { // get line and buffer from ThreadLocals SourceDataLine line = (SourceDataLine) localLine.get(); byte[] buffer = (byte[]) localBuffer.get(); if (line == null || buffer == null) { // the line is unavailable return; } // copy data to the line try { int numBytesRead = 0; while (numBytesRead != -1) { // if paused, wait until unpaused synchronized (pausedLock) { if (paused) { try { pausedLock.wait(); } catch (InterruptedException ex) { return; } } } // copy data numBytesRead = source.read(buffer, 0, buffer.length); if (numBytesRead != -1) { line.write(buffer, 0, numBytesRead); } } } catch (IOException ex) { ex.printStackTrace(); } }
/** 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(); } }
/** Signals that a PooledThread has started. Creates the Thread's line and buffer. */ protected void threadStarted() { // wait for the SoundManager constructor to finish synchronized (this) { try { wait(); } catch (InterruptedException ex) { } } // use a short, 100ms (1/10th sec) buffer for filters that // change in real-time int bufferSize = playbackFormat.getFrameSize() * Math.round(playbackFormat.getSampleRate() / 10); // create, open, and start the line SourceDataLine line; DataLine.Info lineInfo = new DataLine.Info(SourceDataLine.class, playbackFormat); try { line = (SourceDataLine) AudioSystem.getLine(lineInfo); line.open(playbackFormat, bufferSize); } catch (LineUnavailableException ex) { // the line is unavailable - signal to end this thread Thread.currentThread().interrupt(); return; } line.start(); // create the buffer byte[] buffer = new byte[bufferSize]; // set this thread's locals localLine.set(line); localBuffer.set(buffer); }