Java Code Examples for javax.sound.sampled.SourceDataLine#start()
The following examples show how to use
javax.sound.sampled.SourceDataLine#start() .
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: 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 2
Source File: Test.java From DTMF-Decoder with MIT License | 6 votes |
private static void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException { byte[] data = new byte[4096]; SourceDataLine line = getLine(targetFormat); if (line != null) { // Start line.start(); int nBytesRead = 0, nBytesWritten = 0; while (nBytesRead != -1) { nBytesRead = din.read(data, 0, data.length); if (nBytesRead != -1) nBytesWritten = line.write(data, 0, nBytesRead); } // Stop line.drain(); line.stop(); line.close(); din.close(); } }
Example 3
Source File: PlayerTest.java From DTMF-Decoder with MIT License | 6 votes |
private void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException { byte[] data = new byte[4096]; SourceDataLine line = getLine(targetFormat); if (line != null) { // Start line.start(); int nBytesRead = 0, nBytesWritten = 0; while (nBytesRead != -1) { nBytesRead = din.read(data, 0, data.length); if (nBytesRead != -1) nBytesWritten = line.write(data, 0, nBytesRead); } // Stop line.drain(); line.stop(); line.close(); din.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: 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 6
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 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: 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 9
Source File: SoundTools.java From MyBox with Apache License 2.0 | 6 votes |
public static void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException { byte[] data = new byte[CommonValues.IOBufferLength]; DataLine.Info info = new DataLine.Info(SourceDataLine.class, targetFormat); SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(targetFormat); if (line != null) { // Start FloatControl vol = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); logger.debug(vol.getValue() + vol.getUnits()); line.start(); int nBytesRead = 0, nBytesWritten = 0; while (nBytesRead != -1) { nBytesRead = din.read(data, 0, data.length); if (nBytesRead != -1) { nBytesWritten = line.write(data, 0, nBytesRead); } } // Stop line.drain(); line.stop(); line.close(); din.close(); } }
Example 10
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 11
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 12
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 13
Source File: SinkAudio.java From FoxTelem with GNU General Public License v3.0 | 5 votes |
public void setDevice(int position) throws LineUnavailableException, IllegalArgumentException { if (position == 0 || position == -1) { initializeOutput(); } else { Mixer appMixer = mixerList[position]; Info sdlLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat); sourceDataLine = (SourceDataLine) appMixer.getLine(sdlLineInfo); sourceDataLine.open(audioFormat); sourceDataLine.start(); } }
Example 14
Source File: SoundMixer.java From jace with GNU General Public License v2.0 | 5 votes |
public synchronized SourceDataLine getLine(Object requester) throws LineUnavailableException { if (activeLines.containsKey(requester)) { return activeLines.get(requester); } SourceDataLine sdl; if (availableLines.isEmpty()) { sdl = getNewLine(); } else { sdl = availableLines.iterator().next(); availableLines.remove(sdl); } activeLines.put(requester, sdl); sdl.start(); return sdl; }
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: TickAtEndOfPlay.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { System.out.println("This test should only be run on Windows."); System.out.println("Make sure that the speakers are connected and the volume is up."); System.out.println("Close all other programs that may use the soundcard."); System.out.println("You'll hear a 2-second tone. when the tone finishes,"); System.out.println(" there should be no noise. If you hear a short tick/noise,"); System.out.println(" the bug still applies."); System.out.println("Press ENTER to continue."); System.in.read(); for (int i = 0; i < args.length; i++) { if (args[i].equals("1")) WorkAround1 = true; if (args[i].equals("2")) WorkAround2 = true; } if (WorkAround1) System.out.println("Using work around1: appending silence"); if (WorkAround2) System.out.println("Using work around2: waiting before close"); int zerolen = 0; // how many 0-bytes will be appended to playback if (WorkAround1) zerolen = 1000; int seconds = 2; int sampleRate = 8000; double frequency = 1000.0; double RAD = 2.0 * Math.PI; AudioFormat af = new AudioFormat((float)sampleRate,8,1,true,true); System.out.println("Format: "+af); DataLine.Info info = new DataLine.Info(SourceDataLine.class,af); SourceDataLine source = (SourceDataLine)AudioSystem.getLine(info); System.out.println("Line: "+source); if (source.toString().indexOf("MixerSourceLine")>=0) { System.out.println("This test only applies to non-Java Sound Audio Engine!"); return; } System.out.println("Opening..."); source.open(af); System.out.println("Starting..."); source.start(); int datalen = sampleRate * seconds; byte[] buf = new byte[datalen+zerolen]; for (int i=0; i<datalen; i++) { buf[i] = (byte)(Math.sin(RAD*frequency/sampleRate*i)*127.0); } System.out.println("Writing..."); source.write(buf,0,buf.length); System.out.println("Draining..."); source.drain(); System.out.println("Stopping..."); source.stop(); if (WorkAround2) { System.out.println("Waiting 200 millis..."); Thread.sleep(200); } System.out.println("Closing..."); source.close(); System.out.println("Done."); }
Example 18
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; }
Example 19
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 20
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; }