Java Code Examples for javax.sound.sampled.SourceDataLine#open()
The following examples show how to use
javax.sound.sampled.SourceDataLine#open() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StdAudio.java From algs4 with GNU General Public License v3.0 | 6 votes |
private static void init() { try { // 44,100 Hz, 16-bit audio, mono, signed PCM, little endian AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, MONO, SIGNED, LITTLE_ENDIAN); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE); // the internal buffer is a fraction of the actual buffer size, this choice is arbitrary // it gets divided because we can't expect the buffered data to line up exactly with when // the sound card decides to push out its samples. buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE/3]; } catch (LineUnavailableException e) { System.out.println(e.getMessage()); } // no sound gets made before this call line.start(); }
Example 2
Source File: SoundUtils.java From Neural-Network-Programming-with-Java-SecondEdition with MIT License | 6 votes |
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(); }
Example 3
Source File: SoundUtils.java From Neural-Network-Programming-with-Java-SecondEdition with MIT License | 6 votes |
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(); }
Example 4
Source File: SinkAudio.java From FoxTelem with GNU General Public License v3.0 | 6 votes |
/** * FIXME: * specify the buffer size in the open(AudioFormat,int) method. A delay of 10ms-100ms will be acceptable for realtime audio. Very low latencies like will * not work on all computer systems, and 100ms or more will probably be annoying for your users. A good tradeoff is, e.g. 50ms. For your audio format, * 8-bit, mono at 44100Hz, a good buffer size is 2200 bytes, which is almost 50ms */ void initializeOutput() { DataLine.Info dataLineInfo = new DataLine.Info( SourceDataLine.class, audioFormat); //line = (TargetDataLine) AudioSystem.getLine(info); //Mixer m = AudioSystem.getMixer(null); try { //sourceDataLine = (SourceDataLine)m.getLine(dataLineInfo); sourceDataLine = (SourceDataLine)AudioSystem.getLine(dataLineInfo); sourceDataLine.open(audioFormat); sourceDataLine.start(); } catch (LineUnavailableException e) { // TODO Auto-generated catch block e.printStackTrace(Log.getWriter()); } }
Example 5
Source File: JoggStreamer.java From RipplePower with Apache License 2.0 | 6 votes |
private void openOutput() throws IOException { AudioFormat audioFormat = new AudioFormat((float) vorbisInfo.rate, 16, vorbisInfo.channels, true, false); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat, AudioSystem.NOT_SPECIFIED); if (!AudioSystem.isLineSupported(info)) { throw new IOException("line format " + info + "not supported"); } try { out = (SourceDataLine) AudioSystem.getLine(info); out.open(audioFormat); } catch (LineUnavailableException e) { throw new IOException("audio unavailable: " + e.toString()); } out.start(); updateVolume(volume); }
Example 6
Source File: OggClip.java From desktopclient-java with GNU General Public License v3.0 | 6 votes |
private void initJavaSound(int channels, int rate) { try { AudioFormat audioFormat = new AudioFormat(rate, 16, channels, true, // PCM_Signed false // littleEndian ); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat, AudioSystem.NOT_SPECIFIED); if (!AudioSystem.isLineSupported(info)) { throw new Exception("Line " + info + " not supported."); } outputLine = (SourceDataLine) AudioSystem.getLine(info); // outputLine.addLineListener(this); outputLine.open(audioFormat); this.rate = rate; this.channels = channels; setBalance(balance); setGain(gain); } catch (Exception ex) { LOGGER.log(Level.WARNING, "can not init sound system", ex); } }
Example 7
Source File: JavaSoundAudioDevice.java From jsyn with Apache License 2.0 | 6 votes |
@Override public void start() { DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); if (!AudioSystem.isLineSupported(info)) { // Handle the error. logger.severe("JavaSoundOutputStream - not supported." + format); } else { try { line = (SourceDataLine) getDataLine(info); int bufferSize = calculateBufferSize(suggestedOutputLatency); line.open(format, bufferSize); logger.fine("Output buffer size = " + bufferSize + " bytes."); line.start(); } catch (Exception e) { e.printStackTrace(); line = null; } } }
Example 8
Source File: LocalPlayerDemo.java From lavaplayer with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws LineUnavailableException, IOException { AudioPlayerManager manager = new DefaultAudioPlayerManager(); AudioSourceManagers.registerRemoteSources(manager); manager.getConfiguration().setOutputFormat(COMMON_PCM_S16_BE); AudioPlayer player = manager.createPlayer(); manager.loadItem("ytsearch: epic soundtracks", new FunctionalResultHandler(null, playlist -> { player.playTrack(playlist.getTracks().get(0)); }, null, null)); AudioDataFormat format = manager.getConfiguration().getOutputFormat(); AudioInputStream stream = AudioPlayerInputStream.createStream(player, format, 10000L, false); SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class, stream.getFormat()); SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(stream.getFormat()); line.start(); byte[] buffer = new byte[COMMON_PCM_S16_BE.maximumChunkSize()]; int chunkSize; while ((chunkSize = stream.read(buffer)) >= 0) { line.write(buffer, 0, chunkSize); } }
Example 9
Source File: SoundTools.java From MyBox with Apache License 2.0 | 5 votes |
public static SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException { DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); SourceDataLine res = (SourceDataLine) AudioSystem.getLine(info); res.open(audioFormat); return res; }
Example 10
Source File: AudioPlayer.java From pumpernickel with MIT License | 5 votes |
/** * Plays audio from the given audio input stream. * * @param stream * the AudioInputStream to play. * @param startTime * the time to skip to when playing starts. A value of zero means * this plays from the beginning, 1 means it skips one second, * etc. * @param listener * an optional Listener to update. * @param cancellable * an optional Cancellable to consult. * @param blocking * whether this call is blocking or not. * @throws LineUnavailableException * if a line is unavailable. * @throws UnsupportedOperationException * if this static method doesn't support playing the stream * argument **/ public static SourceDataLine playAudioStream(AudioInputStream stream, StartTime startTime, Listener listener, Cancellable cancellable, boolean blocking) throws UnsupportedOperationException, LineUnavailableException { AudioFormat audioFormat = stream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); if (!AudioSystem.isLineSupported(info)) { throw new UnsupportedOperationException( "AudioPlayback.playAudioStream: info=" + info); } final SourceDataLine dataLine = (SourceDataLine) AudioSystem .getLine(info); dataLine.open(audioFormat); dataLine.start(); PlayAudioThread thread = new PlayAudioThread(stream, startTime, dataLine, listener, cancellable); if (blocking) { thread.run(); } else { thread.start(); } return dataLine; }
Example 11
Source File: ChangingBuffer.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private static boolean doMixerSDL(Mixer mixer, AudioFormat format) { if (mixer==null) return false; try { System.out.println("Trying mixer "+mixer+":"); DataLine.Info info = new DataLine.Info( SourceDataLine.class, format, (int) samplerate); SourceDataLine sdl = (SourceDataLine) mixer.getLine(info); System.out.println(" - got sdl: "+sdl); System.out.println(" - open with format "+format); sdl.open(format); System.out.println(" - start..."); sdl.start(); System.out.println(" - write..."); sdl.write(buffer, 0, buffer.length); Thread.sleep(200); System.out.println(" - drain..."); sdl.drain(); System.out.println(" - stop..."); sdl.stop(); System.out.println(" - close..."); sdl.close(); System.out.println(" - closed"); } catch (Throwable t) { System.out.println(" - Caught exception. Not failed."); System.out.println(" - "+t.toString()); return false; } return true; }
Example 12
Source File: LWaveSound.java From RipplePower with Apache License 2.0 | 5 votes |
private SourceDataLine getLine(AudioInputStream ain, AudioFormat audioFormat) throws LineUnavailableException { DataLine.Info info = new DataLine.Info(SourceDataLine.class, ain.getFormat(), ((int) ain.getFrameLength() * audioFormat.getFrameSize())); clip = (SourceDataLine) AudioSystem.getLine(info); clip.open(audioFormat); return clip; }
Example 13
Source File: SDLLinuxCrash.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public static SourceDataLine start() throws Exception { AudioFormat format = new AudioFormat(44100, 16, 2, true, false); if (addLen) { staticLen+=(int) (staticLen/5)+1000; } else { staticLen-=(int) (staticLen/5)+1000; } if (staticLen>8*44100*4) { staticLen = 8*44100*4; addLen=!addLen; } if (staticLen<1000) { staticLen = 1000; addLen=!addLen; } int len = staticLen; len -= (len % 4); out(" preparing to play back "+len+" bytes == "+bytes2Ms(len, format)+"ms audio..."); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); SourceDataLine sdl = (SourceDataLine) AudioSystem.getLine(info); sdl.addLineListener(new LineListener() { public void update(LineEvent e) { if (e.getType() == LineEvent.Type.STOP) { out(" calling close() from event dispatcher thread"); ((SourceDataLine) e.getSource()).close(); } else if (e.getType() == LineEvent.Type.CLOSE) { } } }); out(" opening..."); sdl.open(); out(" starting..."); sdl.start(); (new Thread(new SDLLinuxCrash(sdl, len))).start(); return sdl; }
Example 14
Source File: AudioPlayer.java From google-assistant-java-demo with GNU General Public License v3.0 | 5 votes |
public void play(byte[] sound) throws AudioException { try { AudioFormat format = AudioUtil.getAudioFormat(audioConf); DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, format); SourceDataLine speakers = (SourceDataLine) AudioSystem.getLine(dataLineInfo); speakers.open(format); speakers.start(); speakers.write(sound, 0, sound.length); speakers.drain(); speakers.close(); } catch (Exception e) { throw new AudioException("Unable to play the response", e); } }
Example 15
Source File: DirectSoundUnderrunSilence.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public static void play(Mixer mixer) { int res = 0; try { println("Getting SDL from mixer..."); source = (SourceDataLine) mixer.getLine(info); println("Opening SDL..."); source.open(audioFormat); println("Writing data to SDL..."); source.write(audioData, 0, audioData.length); println("Starting SDL..."); source.start(); println("Now open your ears:"); println("You should have heard a short tone,"); println("followed by silence (no repeating tones)."); key(); source.write(audioData, 0, audioData.length); println("Now you should have heard another short tone."); println("If you did not hear a second tone, or more than 2 tones,"); println("the test is FAILED."); println("otherwise, if you heard a total of 2 tones, the bug is fixed."); key(); } catch (IllegalArgumentException iae) { println("IllegalArgumentException: "+iae.getMessage()); println("Sound device cannot handle this audio format."); println("ERROR: Test environment not correctly set up."); if (source!=null) { source.close(); source = null; } return; } catch (LineUnavailableException lue) { println("LineUnavailableException: "+lue.getMessage()); println("This is normal for some mixers."); } catch (Exception e) { println("Unexpected Exception: "+e.toString()); } if (source != null) { println("Stopping..."); source.stop(); println("Closing..."); source.close(); println("Closed."); source = null; } }
Example 16
Source File: DirectSoundRepeatingBuffer.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public static void play(Mixer mixer) { int res = 0; try { println("Getting SDL from mixer..."); source = (SourceDataLine) mixer.getLine(info); println("Opening SDL..."); source.open(audioFormat); println("Writing data to SDL..."); source.write(audioData, 0, audioData.length); println("Starting SDL..."); source.start(); println("Now open your ears:"); println("- you should have heard a short tone,"); println(" followed by silence."); println("- if after a while you hear repeated tones,"); println(" the bug is NOT fixed."); println("- if the program remains silent after the "); println(" initial tone, the bug is fixed."); key(); } catch (IllegalArgumentException iae) { println("IllegalArgumentException: "+iae.getMessage()); println("Sound device cannot handle this audio format."); println("ERROR: Test environment not correctly set up."); if (source!=null) { source.close(); source = null; } return; } catch (LineUnavailableException lue) { println("LineUnavailableException: "+lue.getMessage()); println("This is normal for some mixers."); } catch (Exception e) { println("Unexpected Exception: "+e.toString()); } if (source != null) { println("Stopping..."); source.stop(); println("Closing..."); source.close(); println("Closed."); source = null; } }
Example 17
Source File: bug6372428.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
void testPlayback() throws LineUnavailableException { // prepare audio data AudioFormat format = new AudioFormat(22050, 8, 1, false, false); byte[] soundData = new byte[(int) (format.getFrameRate() * format.getFrameSize() * DATA_LENGTH)]; // create & open source data line //SourceDataLine line = AudioSystem.getSourceDataLine(format); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); SourceDataLine line = (SourceDataLine)AudioSystem.getLine(info); line.open(format); // start write data thread WriteThread p1 = new WriteThread(line, soundData); p1.start(); // start line PlayThread p2 = new PlayThread(line); p2.start(); // monitor line long lineTime1 = line.getMicrosecondPosition() / 1000; long realTime1 = currentTimeMillis(); while (true) { delay(500); if (!line.isActive()) { log("audio data played completely"); break; } long lineTime2 = line.getMicrosecondPosition() / 1000; long realTime2 = currentTimeMillis(); long dLineTime = lineTime2 - lineTime1; long dRealTime = realTime2 - realTime1; log("line pos: " + lineTime2 + "ms" + ", thread is " + (p2.isAlive() ? "alive" : "DIED")); if (dLineTime < 0) { throw new RuntimeException("ERROR: line position have decreased from " + lineTime1 + " to " + lineTime2); } if (dRealTime < 450) { // delay() has been interrupted? continue; } lineTime1 = lineTime2; realTime1 = realTime2; } }
Example 18
Source File: ToneGenerator.java From jmbe with GNU General Public License v3.0 | 4 votes |
/** * Test harness * @param args not used */ public static void main(String[] args) { ToneGenerator toneGenerator = new ToneGenerator(); AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000.0f, 16, 1, 2, 8000.0f, false); DataLine.Info datalineinfo = new DataLine.Info(SourceDataLine.class, audioFormat); if(AudioSystem.isLineSupported(datalineinfo)) { try { SourceDataLine sourceDataLine = AudioSystem.getSourceDataLine(audioFormat); sourceDataLine.open(audioFormat); for(Tone tone: Tone.DTMF_TONES) // for(Tone tone: Tone.KNOX_TONES) // for(Tone tone: Tone.CALL_PROGRESS_TONES) // for(Tone tone: Tone.DISCRETE_TONES) // for(Tone tone: Tone.values()) { for(int x = 0; x < 128; x++) //Amplitude levels 0 - 127 { System.out.print("\rTONE [" + tone.name() + "]: " + tone + " " + tone.getFrequency1() + (tone.hasFrequency2() ? " PLUS " + tone.getFrequency2() : "") + " AMPLITUDE:" + x); ToneParameters toneParameters = new ToneParameters(tone, x); float[] samples = toneGenerator.generate(toneParameters); ByteBuffer converted = ByteBuffer.allocate(samples.length * 2); converted.order(ByteOrder.LITTLE_ENDIAN); for(float sample : samples) { converted.putShort((short)(sample * Short.MAX_VALUE)); } byte[] bytes = converted.array(); sourceDataLine.write(bytes, 0, bytes.length); if(x == 0) { sourceDataLine.start(); } } System.out.println("\rTONE [" + tone.name() + "]: " + tone + " " + tone.getFrequency1() + (tone.hasFrequency2() ? " PLUS " + tone.getFrequency2() : "")); } } catch(Exception e) { e.printStackTrace(); } } else { System.out.println("Audio Format Not Supported by Host Audio System: " + audioFormat); } }
Example 19
Source File: ClassicDoomSoundDriver.java From mochadoom with GNU General Public License v3.0 | 4 votes |
@Override public boolean InitSound() { // Secure and configure sound device first. System.out.println("I_InitSound: "); // We only need a single data line. // PCM, signed, 16-bit, stereo, 22025 KHz, 2048 bytes per "frame", // maximum of 44100/2048 "fps" AudioFormat format = new AudioFormat(SAMPLERATE, 16, 2, true, true); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); if (AudioSystem.isLineSupported(info)) try { line = (SourceDataLine) AudioSystem.getSourceDataLine(format); line.open(format,AUDIOLINE_BUFFER); } catch (Exception e) { e.printStackTrace(); System.err.print("Could not play signed 16 data\n"); return false; } if (line != null) { System.err.print(" configured audio device\n"); line.start(); } else { System.err.print(" could not configure audio device\n"); return false; } // This was here only for debugging purposes /* * try { fos=new FileOutputStream("test.raw"); dao=new * DataOutputStream(fos); } catch (FileNotFoundException e) { * Auto-generated catch block e.printStackTrace(); } */ SOUNDSRV = new MixServer(line); SOUNDTHREAD = new Thread(SOUNDSRV); SOUNDTHREAD.start(); // Initialize external data (all sounds) at start, keep static. System.err.print("I_InitSound: "); super.initSound8(); System.err.print(" pre-cached all sound data\n"); // Now initialize mixbuffer with zero. initMixBuffer(); // Finished initialization. System.err.print("I_InitSound: sound module ready\n"); return true; }
Example 20
Source File: PlaySine.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public static int play(boolean shouldPlay) { int res = 0; DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); try { println("Getting line from mixer..."); source = (SourceDataLine) mixer.getLine(info); println("Opening line..."); println(" -- if the program is hanging here, kill the process that has blocks the audio device now."); source.open(audioFormat); println("Starting line..."); source.start(); println("Writing audio data for 1 second..."); long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < 1000) { writeData(); Thread.sleep(100); } res = 1; } catch (IllegalArgumentException iae) { println("IllegalArgumentException: "+iae.getMessage()); println("Sound device cannot handle this audio format."); println("ERROR: Test environment not correctly set up."); if (source!=null) { source.close(); } return 3; } catch (LineUnavailableException lue) { println("LineUnavailableException: "+lue.getMessage()); if (shouldPlay) { println("ERROR: the line should be available now!."); println(" Verify that you killed the other audio process."); } else { println("Correct behavior! the bug is fixed."); } res = 2; } catch (Exception e) { println("Unexpected Exception: "+e.toString()); } if (source != null) { println("Draining..."); try { source.drain(); } catch (NullPointerException npe) { println("(NullPointerException: bug fixed in J2SE 1.4.2"); } println("Stopping..."); source.stop(); println("Closing..."); source.close(); source = null; } return res; }