public void run(String local, String remote, InputStream pin, OutputStream pout) { try { microphone = SoundMixerEnumerator.getInputLine(pcmformat, DefaultPhonePCMBlockSize); } catch (LineUnavailableException lue) { System.out.println( "\3b" + getClass().getName() + ".<init>:\n\tCould not create microphone input stream.\n\t" + lue); } try { speaker = SoundMixerEnumerator.getOutputLine(pcmformat, DefaultPhonePCMBlockSize); } catch (LineUnavailableException lue) { microphone.close(); System.out.println( "\3b" + getClass().getName() + ".<init>:\n\tCould not create speaker output stream.\n\t" + lue); } if ((speaker == null) || (microphone == null)) { super.run(local, remote, pin, pout); return; } try { recorder = new Recorder(pout); recorder.start(); gui = openMonitorGUI("Remote " + remote + " Local " + local); pin.skip(pin.available()); // waste whatever we couldn't process in time super.run(local, remote, new PhoneCallMonitorInputStream(pin), pout); recorder.interrupt(); gui.dispose(); } catch (Exception e) { System.out.println("3\b" + getClass().getName() + ".run:\n\t" + e); e.printStackTrace(); } finally { deactivate(); microphone.close(); speaker.close(); if (gui != null) { gui.dispose(); } } }
public void play(InputStream source) { int bufferSize = format.getFrameSize() * Math.round(format.getSampleRate() / 10); byte[] buffer = new byte[bufferSize]; SourceDataLine line; 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; } line.start(); try { int numBytesRead = 0; while (numBytesRead != -1) { numBytesRead = source.read(buffer, 0, buffer.length); if (numBytesRead != -1) line.write(buffer, 0, numBytesRead); } } catch (IOException e) { e.printStackTrace(); } line.drain(); line.close(); }
/** 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(); } }
// @Test public void playTest() throws Exception { logger.info("start playTest"); SourceDataLine audioLine = null; MediaAudio samples = beepSamples(); logger.info("sample is ready"); AudioFormat format = new AudioFormat( (float) samples.getSampleRate(), (int) samples.getBytesPerSample() * 8, samples.getChannels(), true, false); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); audioLine = (SourceDataLine) AudioSystem.getLine(info); audioLine.open(format); logger.info("beepstart"); audioLine.start(); Buffer buffer = samples.getData(0); audioLine.write( buffer.getByteArray(0, samples.getDataPlaneSize(0)), 0, samples.getDataPlaneSize(0)); audioLine.drain(); logger.info("beepend"); audioLine.close(); audioLine = null; }
public synchronized void done() { if (done) { return; } done = true; /* * There seems to be a bug in the Sun Ray audio system * where close() hangs sometimes if there is still data * in the speaker buffer. By sleeping for the time * it would take to empty a full buffer (plus some slop), * the close() seems to always complete. * * XXX */ try { Thread.sleep(getBufferSizeMillis() + RtpPacket.PACKET_PERIOD); } catch (InterruptedException e) { } synchronized (speaker) { speaker.flush(); speaker.stop(); speaker.close(); } if (Logger.logLevel >= Logger.LOG_MOREINFO) { Logger.println("Speaker closed"); } }
public static void sound(double hz, int msecs, double vol) throws LineUnavailableException { if (hz <= 0) throw new IllegalArgumentException("Frequency <= 0 hz"); if (msecs <= 0) throw new IllegalArgumentException("Duration <= 0 msecs"); if (vol > 1.0 || vol < 0.0) throw new IllegalArgumentException("Volume out of range 0.0 - 1.0"); byte[] buf = new byte[(int) SAMPLE_RATE * msecs / 1000]; for (int i = 0; i < buf.length; i++) { double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI; buf[i] = (byte) (Math.sin(angle) * 127.0 * vol); } // shape the front and back 10ms of the wave form for (int i = 0; i < SAMPLE_RATE / 100.0 && i < buf.length / 2; i++) { buf[i] = (byte) (buf[i] * i / (SAMPLE_RATE / 100.0)); buf[buf.length - 1 - i] = (byte) (buf[buf.length - 1 - i] * i / (SAMPLE_RATE / 100.0)); } AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, false); SourceDataLine sdl = AudioSystem.getSourceDataLine(af); sdl.open(af); sdl.start(); sdl.write(buf, 0, buf.length); sdl.drain(); sdl.close(); }
private void doPlay(File file) { AudioInputStream actualAudioIn = null; this.file = file; try (AudioInputStream audioIn = AudioSystem.getAudioInputStream(file)) { AudioFormat baseFormat = audioIn.getFormat(); System.out.println(baseFormat.getEncoding()); AudioFormat decodedFormat = getDecodedFormat(baseFormat); // make new audio in stream based on decoded format actualAudioIn = AudioSystem.getAudioInputStream(decodedFormat, audioIn); // get data from audio system line = getLine(decodedFormat); line.addLineListener(this); doPlay(decodedFormat, actualAudioIn); audioIn.close(); } catch (Exception e) { logger.log(Level.WARNING, "Exception playing file '" + file.getName() + "'", e); } finally { if (actualAudioIn != null) { try { actualAudioIn.close(); } catch (IOException e) { } } if (line != null) line.close(); } }
public static void warp(int repeat) throws LineUnavailableException, InterruptedException { AudioFormat af = new AudioFormat( SAMPLE_RATE, // sampleRate 8, // sampleSizeInBits 1, // channels true, // signed false); // bigEndian SourceDataLine sdl = AudioSystem.getSourceDataLine(af); sdl.open(af); sdl.start(); byte[] buf = new byte[1]; int step; for (int j = 0; j < repeat; j++) { step = 25; for (int i = 0; i < 2000; i++) { if (i < 500) { buf[0] = ((i % step > 0) ? 32 : (byte) 0); if (i % 25 == 0) step--; } else { buf[0] = ((i % step > 0) ? 16 : (byte) 0); if (i % 50 == 0) step++; } sdl.write(buf, 0, 1); } } sdl.drain(); sdl.stop(); sdl.close(); }
public static void bang() throws LineUnavailableException, InterruptedException { AudioFormat af = new AudioFormat( SAMPLE_RATE, // sampleRate 8, // sampleSizeInBits 1, // channels true, // signed false); // bigEndian SourceDataLine sdl = AudioSystem.getSourceDataLine(af); sdl.open(af); sdl.start(); byte[] buf = new byte[1]; Random r = new Random(); boolean silence = true; for (int i = 0; i < 8000; i++) { while (r.nextInt() % 10 != 0) { buf[0] = silence ? 0 : (byte) Math.abs( r.nextInt() % (int) (1. + 63. * (1. + Math.cos(((double) i) * Math.PI / 8000.)))); i++; sdl.write(buf, 0, 1); } silence = !silence; } sdl.drain(); sdl.stop(); sdl.close(); }
@Override public void onInactive() { if (audioLine != null) { audioLine.flush(); audioLine.close(); audioLine = null; } }
public void run() { File soundFile = new File(filename); if (!soundFile.exists()) { System.err.println("Wave file not found: " + filename); Dialog.erreur(null, "Le fichier " + filename + " n'a pas été trouver."); return; } AudioInputStream audioInputStream = null; try { audioInputStream = AudioSystem.getAudioInputStream(soundFile); } catch (UnsupportedAudioFileException e1) { e1.printStackTrace(); return; } catch (IOException e1) { e1.printStackTrace(); return; } AudioFormat format = audioInputStream.getFormat(); SourceDataLine auline = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); try { auline = (SourceDataLine) AudioSystem.getLine(info); auline.open(format); } catch (LineUnavailableException e) { e.printStackTrace(); return; } catch (Exception e) { e.printStackTrace(); return; } if (auline.isControlSupported(FloatControl.Type.PAN)) { FloatControl pan = (FloatControl) auline.getControl(FloatControl.Type.PAN); if (curPosition == Position.RIGHT) pan.setValue(1.0f); else if (curPosition == Position.LEFT) pan.setValue(-1.0f); } auline.start(); int nBytesRead = 0; byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; try { while (nBytesRead != -1) { nBytesRead = audioInputStream.read(abData, 0, abData.length); if (nBytesRead >= 0) auline.write(abData, 0, nBytesRead); } } catch (IOException e) { e.printStackTrace(); return; } finally { auline.drain(); auline.close(); } }
/** Free the data line. */ public void close() { logger.info("closing..."); controls.clear(); if (codec != null) { codec.close(); codec = null; } sourceLine.close(); sourceLine = null; }
public void run() { File soundFile = new File(this.filename); if (!soundFile.exists()) { System.err.println("nicht gefunden: " + filename); return; } AudioInputStream audioInputStream = null; try { audioInputStream = AudioSystem.getAudioInputStream(soundFile); } catch (UnsupportedAudioFileException e1) { e1.printStackTrace(); return; } catch (IOException e1) { e1.printStackTrace(); return; } AudioFormat format = audioInputStream.getFormat(); SourceDataLine auline = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); try { auline = (SourceDataLine) AudioSystem.getLine(info); auline.open(format); } catch (LineUnavailableException e) { e.printStackTrace(); return; } catch (Exception e) { e.printStackTrace(); return; } FloatControl rate = (FloatControl) auline.getControl(FloatControl.Type.SAMPLE_RATE); rate.setValue(rate.getValue() * 5f); auline.start(); int nBytesRead = 0; byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; try { while (nBytesRead != -1) { nBytesRead = audioInputStream.read(abData, 0, abData.length); if (nBytesRead >= 0) auline.write(abData, 0, nBytesRead); } } catch (IOException e) { e.printStackTrace(); return; } finally { auline.drain(); auline.close(); } }
/* * Taken from the JOrbis Player */ private SourceDataLine getOutputLine(int channels, int rate) { if (outputLine == null || this.rate != rate || this.channels != channels) { if (outputLine != null) { outputLine.drain(); outputLine.stop(); outputLine.close(); } initJavaSound(channels, rate); outputLine.start(); } return outputLine; }
public boolean close() { boolean res = true; try { sdl.stop(); sdl.close(); } catch (Exception e) { Logger.warning("Could not close or stop SoundDataLine: " + sdl); res = false; } opened = false; return res; }
// http://stackoverflow.com/questions/13789063/get-sound-from-a-url-with-java private void playMP3(final String url) { try { // Create the JavaFX Panel for the WebView JFXPanel fxPanel = new JFXPanel(); fxPanel.setLocation(new Point(0, 0)); // Initialize the webView in a JavaFX-Thread Platform.runLater( new Runnable() { public void run() { MediaPlayer player = new MediaPlayer(new Media(url)); player.play(); } }); if (true) return; AudioInputStream in = AudioSystem.getAudioInputStream(new URL(url)); AudioFormat baseFormat = in.getFormat(); AudioFormat decodedFormat = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); AudioInputStream din = AudioSystem.getAudioInputStream(decodedFormat, in); DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat); SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); if (line != null) { line.open(decodedFormat); byte[] data = new byte[4096]; // Start line.start(); int nBytesRead; while ((nBytesRead = din.read(data, 0, data.length)) != -1) { line.write(data, 0, nBytesRead); } // Stop line.drain(); line.stop(); line.close(); din.close(); } } catch (Exception e) { App.debug("playing MP3 failed " + url + " " + e.toString()); } }
private static void closeJavaSound() { if (mLine != null) { /* * Wait for the line to finish playing */ mLine.drain(); /* * Close the line. */ mLine.close(); mLine = null; } }
/** @param filename the name of the file that is going to be played */ public void playSound(String filename) { String strFilename = filename; try { soundFile = new File(strFilename); } catch (Exception e) { e.printStackTrace(); System.exit(1); } try { audioStream = AudioSystem.getAudioInputStream(soundFile); } catch (Exception e) { e.printStackTrace(); System.exit(1); } audioFormat = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); try { sourceLine = (SourceDataLine) AudioSystem.getLine(info); sourceLine.open(audioFormat); } catch (LineUnavailableException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { e.printStackTrace(); System.exit(1); } sourceLine.start(); int nBytesRead = 0; byte[] abData = new byte[BUFFER_SIZE]; while (nBytesRead != -1) { try { nBytesRead = audioStream.read(abData, 0, abData.length); } catch (IOException e) { e.printStackTrace(); } if (nBytesRead >= 0) { @SuppressWarnings("unused") int nBytesWritten = sourceLine.write(abData, 0, nBytesRead); } } sourceLine.drain(); sourceLine.close(); }
/** * Sets the value of output to newOutput. The output variable specifies whether or not to play the * audio of this source on the server. * * @param newOutput The new value for output. */ public void setOutput(boolean newOutput) { output = newOutput; if (output) { try { serverOutput.open(); } catch (LineUnavailableException e) { e.printStackTrace(); } serverOutput.start(); } else { serverOutput.stop(); serverOutput.close(); } }
/** Inits Audio ressources from AudioSystem.<br> */ protected void initLine() throws LineUnavailableException { log.info("initLine()"); if (m_line == null) { createLine(); } if (!m_line.isOpen()) { openLine(); } else { AudioFormat lineAudioFormat = m_line.getFormat(); AudioFormat audioInputStreamFormat = m_audioInputStream == null ? null : m_audioInputStream.getFormat(); if (!lineAudioFormat.equals(audioInputStreamFormat)) { m_line.close(); openLine(); } } }
@Override public void onActive() { if (audioLine != null) audioLine.close(); try { if (player.getMixer() != null) { log.debug("Custom mixer " + player.getMixer().getName()); audioLine = AudioSystem.getSourceDataLine(PCM, player.getMixer()); } else { audioLine = AudioSystem.getSourceDataLine(PCM); } audioLine.open(PCM, 1048576); onVolumeChanged(player.getVolume()); if (isMuted && audioLine.isControlSupported(BooleanControl.Type.MUTE)) ((BooleanControl) audioLine.getControl(BooleanControl.Type.MUTE)).setValue(true); } catch (LineUnavailableException e) { log.error("onActive error", e); } }
protected void reset() { m_status = UNKNOWN; if (m_audioInputStream != null) { synchronized (m_audioInputStream) { closeStream(); } } m_audioInputStream = null; m_audioFileFormat = null; m_encodedaudioInputStream = null; encodedLength = -1; if (m_line != null) { m_line.stop(); m_line.close(); m_line = null; } m_gainControl = null; m_panControl = null; }
// 播放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(); } }
/** * Play a sound. * * @param in The <code>AudioInputStream</code> to play. * @return True if the stream was played without incident. */ private boolean playSound(AudioInputStream in) throws IOException { boolean ret = false; SourceDataLine line = openLine(in.getFormat()); if (line == null) return false; try { startPlaying(); int rd; while (keepPlaying() && (rd = in.read(data)) > 0) { line.write(data, 0, rd); } ret = true; } finally { stopPlaying(); line.drain(); line.stop(); line.close(); } return ret; }
public void run() { try { sourceDataLine = (SourceDataLine) AudioSystem.getLine(info); sourceDataLine.open(format, bufferSize); sourceDataLine.start(); } catch (LineUnavailableException ex) { System.out.println("Unable to open the line: " + ex); return; } try { byte[] data = new byte[bufferSize]; int numBytesRead = 0; int written = 0; while (running) { try { if ((numBytesRead = audioInputStrem.read(data)) == -1) break; int numBytesRemaining = numBytesRead; while (numBytesRemaining > 0) { written = sourceDataLine.write(data, 0, numBytesRemaining); numBytesRemaining -= written; } } catch (ArrayIndexOutOfBoundsException ae) { /** * Some capture devices eventually deliver larger buffers than they originally say they * would. Catch that and reset the data buffer */ bufferSize = numBytesRead; data = new byte[bufferSize]; } catch (Exception e) { e.printStackTrace(); System.out.println("Error during playback: " + e); break; } } sourceDataLine.stop(); sourceDataLine.flush(); sourceDataLine.close(); } catch (Exception e) { } }
public static void playBackAudioFile() { String strFilename = "/tmp/RecordAudio-toGSM.wav"; File soundFile = new File(strFilename); AudioInputStream audioInputStream = null; try { audioInputStream = AudioSystem.getAudioInputStream(soundFile); } catch (Exception e) { e.printStackTrace(); System.exit(1); } AudioFormat audioFormat = audioInputStream.getFormat(); SourceDataLine line = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); try { line = (SourceDataLine) AudioSystem.getLine(info); line.open(audioFormat); } catch (LineUnavailableException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { e.printStackTrace(); System.exit(1); } line.start(); int nBytesRead = 0; byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; while (nBytesRead != -1) { try { nBytesRead = audioInputStream.read(abData, 0, abData.length); } catch (IOException e) { e.printStackTrace(); } if (nBytesRead >= 0) { int nBytesWritten = line.write(abData, 0, nBytesRead); } } line.drain(); line.close(); System.exit(0); }
public static void tone(int hz, int msecs, double vol) throws LineUnavailableException { byte[] buf = new byte[1]; AudioFormat af = new AudioFormat( SAMPLE_RATE, // sampleRate 8, // sampleSizeInBits 1, // channels true, // signed false); // bigEndian SourceDataLine sdl = AudioSystem.getSourceDataLine(af); sdl.open(af); sdl.start(); for (int i = 0; i < msecs * 8; i++) { double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI; buf[0] = (byte) (Math.sin(angle) * 127.0 * vol); sdl.write(buf, 0, 1); } sdl.drain(); sdl.stop(); sdl.close(); }
public void run() { try { URL defaultSound = getClass().getResource("/sounds/lauf3.wav"); // Sound // aus // dem // Package File file1 = new File(defaultSound.toURI()); // Soundfile laden AudioInputStream audioInputStream = AudioSystem // und in den // "Stream" packen .getAudioInputStream(file1); AudioFormat af = audioInputStream.getFormat(); // Format holen fuer // spaeter SourceDataLine line = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, af); line = (SourceDataLine) AudioSystem.getLine(info); line.open(af); line.start(); int BUFFER_SIZE = 64 * 1024; int Byteslesen = 0; byte[] sampledData = new byte[BUFFER_SIZE]; do { while (Byteslesen != -1) { if (JMenue.stopper == true) { // beenden falls Menue zu Byteslesen = audioInputStream.read(sampledData, 0, sampledData.length); if (Byteslesen >= 0) { line.write(sampledData, 0, Byteslesen); } } else if (JMenue.stopper == false) { line.close(); } } } while (line.isActive()); } catch (Exception e) { // Fehler auffangen e.printStackTrace(); } return; }
public void run() { // --------------init SourceDataLine sdl = Central.getGoutputSelector().getSourceDataLine(); TargetDataLine tdl = Central.getGinputSelector().getTargetDataLine(); try { tdl.open(af, READ_BUFFER_SIZE); sdl.open(af, WRITE_BUFFER_SIZE); sdl.start(); tdl.start(); while (checkRunning()) { tdl.read(sbMove, 0, READSIZE); sdl.write(sbMove, 0, READSIZE); } tdl.close(); sdl.close(); } catch (LineUnavailableException e) { e.printStackTrace(); } error.log("Continuous Loop Stopped"); }