Java Code Examples for javax.sound.sampled.SourceDataLine#close()

The following examples show how to use javax.sound.sampled.SourceDataLine#close() . 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 vote down vote up
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 vote down vote up
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 vote down vote up
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: Sounds.java    From open-ig with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** Close all audio lines. */
public void close() {
	if (exec != null) {
		exec.shutdown();
		for (SourceDataLine sdl : lines) {
			sdl.close();
		}
		try {
			exec.awaitTermination(60, TimeUnit.SECONDS);
		} catch (InterruptedException ex) {
			// ignored
		}
		exec.shutdownNow();
		lines.clear();
		soundPool.clear();
		soundMap.clear();
		soundFormat.clear();
		exec = null;
	}
	
}
 
Example 5
Source File: AquaAudioListUI.java    From pumpernickel with MIT License 6 votes vote down vote up
@Override
public boolean isVisible(JList list, Object value, int row,
		boolean isSelected, boolean cellHasFocus) {
	URL sound = (URL) value;
	SoundUI ui = getSoundUI(sound);

	if (!isSelected) {
		SourceDataLine dataLine = ui.line;
		if (dataLine != null)
			dataLine.close();
	}

	boolean visible = isSelected;
	if (!visible) {
		ui.setTargetOpacity(0);
	}
	if (ui.targetOpacity > 0)
		visible = true;
	return visible;
}
 
Example 6
Source File: SoundUtils.java    From Neural-Network-Programming-with-Java-SecondEdition with MIT License 6 votes vote down vote up
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 7
Source File: SoundTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
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 8
Source File: SDLLinuxCrash.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (!isSoundcardInstalled()) {
        return;
    }

    try {
        int COUNT=10;
        out();
        out("4498848 Sound causes crashes on Linux (testing with SourceDataLine)");
        if (args.length>0) {
            COUNT=Integer.parseInt(args[0]);
        }
        for (int i=0; i<COUNT; i++) {
            out("  trial "+(i+1)+"/"+COUNT);
            SourceDataLine sdl = start();
            int waitTime = 500+(1000*(i % 2)); // every 2nd time wait 1500, rather than 500ms.
            out("    waiting for "+waitTime+" ms for audio playback to stop...");
            Thread.sleep(waitTime);
            out("    calling close() from main thread");
            sdl.close();
            // let the subsystem enough time to actually close the soundcard
            out("    waiting for 2 seconds...");
            Thread.sleep(2000);
            out();
        }
        out("  waiting for 1 second...");
        Thread.sleep(1000);
    } catch (Exception e) {
        e.printStackTrace();
        out("  waiting for 1 second");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ie) {}
        // do not fail if no audio device installed - bug 4742021
        if (!(e instanceof LineUnavailableException)) {
            throw e;
        }
    }
    out("Test passed");
}
 
Example 9
Source File: LongFramePosition.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    boolean failed = false;
    try {
        AudioFormat format = new AudioFormat(44100.0f, 16, 2, true, false);
        SourceDataLine sdl = AudioSystem.getSourceDataLine(format);
        try {
            sdl.open(format);
            sdl.start();
            sdl.write(new byte[16384], 0, 16384);
            Thread.sleep(1000);
            int intPos = sdl.getFramePosition();
            long longPos = sdl.getLongFramePosition();
            System.out.println("After 1 second: getFramePosition() = "+intPos);
            System.out.println("            getLongFramePosition() = "+longPos);
            if (intPos <= 0 || longPos <= 0) {
                failed = true;
                System.out.println("## FAILED: frame position did not advance, or negative!");
            }
            if (Math.abs(intPos - longPos) > 100) {
                failed = true;
                System.out.println("## FAILED: frame positions are not the same!");
            }
        } finally {
            sdl.close();
        }
    } catch (LineUnavailableException | IllegalArgumentException e) {
        System.out.println(e);
        System.out.println("Cannot execute test.");
        return;
    }
    if (failed) throw new RuntimeException("Test FAILED!");
    System.out.println("Test Passed.");
}
 
Example 10
Source File: BufferSizeCheck.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    boolean realTest = false;
    if (!isSoundcardInstalled()) {
        return;
    }

    try {
        out("4661602: Buffersize is checked when re-opening line");
        AudioFormat format = new AudioFormat(44100, 16, 2, true, false);
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
        SourceDataLine sdl = (SourceDataLine) AudioSystem.getLine(info);
        out("Opening with buffersize 12000...");
        sdl.open(format, 12000);
        out("Opening with buffersize 11000...");
        realTest=true;
        sdl.open(format, 11000);
        try {
            sdl.close();
        } catch(Throwable t) {}
    } catch (Exception e) {
        e.printStackTrace();
        // do not fail if no audio device installed - bug 4742021
        if (realTest || !(e instanceof LineUnavailableException)) {
            throw e;
        }
    }
    out("Test passed");
}
 
Example 11
Source File: ChangingBuffer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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: SoundPlayer.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Play a sound.
 *
 * @param sound The {@code File} to play.
 * @return True if the sound was played without incident.
 * @exception IOException if unable to read or write the sound data.
 */
private boolean playSound(File sound) throws IOException {
    boolean ret = false;
    try (AudioInputStream in = getAudioInputStream(sound)) {
        SourceDataLine line = openLine(in.getFormat(), getMixer(),
                                       data.length);
        if (line == null) return false;
        changeVolume(line, getVolume());
        try {
            this.playDone = false;
            int rd;
            while (!this.playDone && (rd = in.read(data)) > 0) {
                line.write(data, 0, rd);
            }
            ret = true;
            //logger.finest("Played " + sound);
        } finally {
            this.playDone = true;
            line.drain();
            line.stop();
            line.close();
        }
    } catch (IOException ioe) {
        logger.log(Level.WARNING, "Can not open "
            + sound + " as audio stream", ioe);
        return false;
    }
    return ret;
}
 
Example 13
Source File: AudioPlayer.java    From google-assistant-java-demo with GNU General Public License v3.0 5 votes vote down vote up
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 14
Source File: PlaySine.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
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 15
Source File: DirectSoundUnderrunSilence.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
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 vote down vote up
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 vote down vote up
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: Sounds.java    From open-ig with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Places back the data line into the pool.
 * @param aft the audio format
 * @param sdl the source data line
 */
void putBackLine(AudioFormatType aft, SourceDataLine sdl) {
       sdl.close();
}