Java Code Examples for javax.sound.sampled.AudioSystem#getLine()

The following examples show how to use javax.sound.sampled.AudioSystem#getLine() . 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: WaveEngine.java    From javagame with MIT License 6 votes vote down vote up
/**
 * WAVE�t�@�C�������[�h
 * @param url WAVE�t�@�C����URL
 */
public static void load(URL url) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
    // �I�[�f�B�I�X�g���[�����J��
    AudioInputStream ais = AudioSystem.getAudioInputStream(url);
    // WAVE�t�@�C���̃t�H�[�}�b�g���擾
    AudioFormat format = ais.getFormat();
    // ���C�����擾
    DataLine.Info info = new DataLine.Info(SourceDataLine.class, format, AudioSystem.NOT_SPECIFIED);

    // WAVE�f�[�^���擾
    DataClip clip = new DataClip(ais);
    
    // WAVE�f�[�^��o�^
    clips[counter] = clip;
    lines[counter] = (SourceDataLine)AudioSystem.getLine(info);
    
    // ���C�����J��
    lines[counter].open(format);

    counter++;
}
 
Example 2
Source File: JavaSoundAudioClip.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private boolean createSourceDataLine() {
    if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createSourceDataLine()");
    try {
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, loadedAudioFormat);
        if (!(AudioSystem.isLineSupported(info)) ) {
            if (DEBUG || Printer.err)Printer.err("Line not supported: "+loadedAudioFormat);
            // fail silently
            return false;
        }
        SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
        datapusher = new DataPusher(source, loadedAudioFormat, loadedAudio, loadedAudioByteLength);
    } catch (Exception e) {
        if (DEBUG || Printer.err)e.printStackTrace();
        // fail silently
        return false;
    }

    if (datapusher==null) {
        // fail silently
        return false;
    }

    if (DEBUG || Printer.debug)Printer.debug("Created SourceDataLine.");
    return true;
}
 
Example 3
Source File: WaveEngine.java    From javagame with MIT License 6 votes vote down vote up
/**
 * WAVE�t�@�C�������[�h
 * @param url WAVE�t�@�C����URL
 */
public static void load(URL url) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
    // �I�[�f�B�I�X�g���[�����J��
    AudioInputStream ais = AudioSystem.getAudioInputStream(url);
    // WAVE�t�@�C���̃t�H�[�}�b�g���擾
    AudioFormat format = ais.getFormat();
    // ���C�����擾
    DataLine.Info info = new DataLine.Info(SourceDataLine.class, format, AudioSystem.NOT_SPECIFIED);

    // WAVE�f�[�^���擾
    DataClip clip = new DataClip(ais);
    
    // WAVE�f�[�^��o�^
    clips[counter] = clip;
    lines[counter] = (SourceDataLine)AudioSystem.getLine(info);
    
    // ���C�����J��
    lines[counter].open(format);

    counter++;
}
 
Example 4
Source File: JavaSoundAudioClip.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private boolean createSourceDataLine() {
    if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createSourceDataLine()");
    try {
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, loadedAudioFormat);
        if (!(AudioSystem.isLineSupported(info)) ) {
            if (DEBUG || Printer.err)Printer.err("Line not supported: "+loadedAudioFormat);
            // fail silently
            return false;
        }
        SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
        datapusher = new DataPusher(source, loadedAudioFormat, loadedAudio, loadedAudioByteLength);
    } catch (Exception e) {
        if (DEBUG || Printer.err)e.printStackTrace();
        // fail silently
        return false;
    }

    if (datapusher==null) {
        // fail silently
        return false;
    }

    if (DEBUG || Printer.debug)Printer.debug("Created SourceDataLine.");
    return true;
}
 
Example 5
Source File: SoundFormat.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
public boolean play(SWFInputStream sis) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (!decode(sis, baos)) {
        return false;
    }

    AudioFormat audioFormat = new AudioFormat(samplingRate, 16, stereo ? 2 : 1, true, false);
    DataLine.Info info = new DataLine.Info(SourceDataLine.class,
            audioFormat);
    try (SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info)) {
        line.open(audioFormat);
        byte[] outData = baos.toByteArray();
        line.write(outData, 0, outData.length);
        line.drain();
        line.stop();
        return true;
    } catch (LineUnavailableException ex) {
        return false;
    }
}
 
Example 6
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 7
Source File: TestDataSetSource.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
protected void openLineIn() {
    final AudioFormat format = new AudioFormat(samplingRate, N_SYNTHESISER_BITS, 1, true, true);
    final DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

    // checks if system supports the data line
    if (!AudioSystem.isLineSupported(info)) {
        LOGGER.atError().addArgument(info).addArgument(format).log("Line not supported '{}' format was '{}'");
        throw new IllegalArgumentException("Line not supported");
    }

    try {
        line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(format);
        if (LOGGER.isInfoEnabled()) {
            LOGGER.atInfo().log("opened audio line-in, format = " + format);
        }
    } catch (final LineUnavailableException e) {
        LOGGER.atError().setCause(e).addArgument(DATA_SOURCE_FILE).log("'{}' does not seem to be recognised as a Midi file");
    }
}
 
Example 8
Source File: UI.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
private void playSirenSound() {
	try {
		File soundFile = new File(sirenFile);
		AudioInputStream soundIn = AudioSystem.getAudioInputStream(soundFile);
		AudioFormat format = soundIn.getFormat();
		DataLine.Info info = new DataLine.Info(Clip.class, format);
		clip = (Clip) AudioSystem.getLine(info);
		clip.addLineListener(new LineListener() {
			@Override
			public void update(LineEvent event) {
				if (event.getType() == LineEvent.Type.STOP) {
					soundOn = false;
				}
			}
		});
		clip.open(soundIn);
		clip.start();
		soundOn = true;
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 9
Source File: IsRunningHang.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void test(final AudioFormat format, final byte[] data)
        throws Exception {
    final Line.Info info = new DataLine.Info(Clip.class, format);
    final Clip clip = (Clip) AudioSystem.getLine(info);

    go = new CountDownLatch(1);
    clip.addLineListener(event -> {
        if (event.getType().equals(LineEvent.Type.START)) {
            go.countDown();
        }
    });

    clip.open(format, data, 0, data.length);
    clip.start();
    go.await();
    while (clip.isRunning()) {
        // This loop should not hang
    }
    while (clip.isActive()) {
        // This loop should not hang
    }
    clip.close();
}
 
Example 10
Source File: JavaSoundAudioClip.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private boolean createClip() {

        if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createClip()");

        try {
            DataLine.Info info = new DataLine.Info(Clip.class, loadedAudioFormat);
            if (!(AudioSystem.isLineSupported(info)) ) {
                if (DEBUG || Printer.err)Printer.err("Clip not supported: "+loadedAudioFormat);
                // fail silently
                return false;
            }
            Object line = AudioSystem.getLine(info);
            if (!(line instanceof AutoClosingClip)) {
                if (DEBUG || Printer.err)Printer.err("Clip is not auto closing!"+clip);
                // fail -> will try with SourceDataLine
                return false;
            }
            clip = (AutoClosingClip) line;
            clip.setAutoClosing(true);
            if (DEBUG || Printer.debug) clip.addLineListener(this);
        } catch (Exception e) {
            if (DEBUG || Printer.err)e.printStackTrace();
            // fail silently
            return false;
        }

        if (clip==null) {
            // fail silently
            return false;
        }

        if (DEBUG || Printer.debug)Printer.debug("Loaded clip.");
        return true;
    }
 
Example 11
Source File: SoundTools.java    From MyBox with Apache License 2.0 5 votes vote down vote up
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 12
Source File: JavaSoundAudioClip.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private boolean createClip() {
    try {
        DataLine.Info info = new DataLine.Info(Clip.class, loadedAudioFormat);
        if (!(AudioSystem.isLineSupported(info)) ) {
            if (Printer.err) Printer.err("Clip not supported: "+loadedAudioFormat);
            // fail silently
            return false;
        }
        Object line = AudioSystem.getLine(info);
        if (!(line instanceof AutoClosingClip)) {
            if (Printer.err) Printer.err("Clip is not auto closing!"+clip);
            // fail -> will try with SourceDataLine
            return false;
        }
        clip = (AutoClosingClip) line;
        clip.setAutoClosing(true);
    } catch (Exception e) {
        if (Printer.err) e.printStackTrace();
        // fail silently
        return false;
    }

    if (clip==null) {
        // fail silently
        return false;
    }
    return true;
}
 
Example 13
Source File: JavaSoundAudioClip.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private boolean createClip() {

        if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createClip()");

        try {
            DataLine.Info info = new DataLine.Info(Clip.class, loadedAudioFormat);
            if (!(AudioSystem.isLineSupported(info)) ) {
                if (DEBUG || Printer.err)Printer.err("Clip not supported: "+loadedAudioFormat);
                // fail silently
                return false;
            }
            Object line = AudioSystem.getLine(info);
            if (!(line instanceof AutoClosingClip)) {
                if (DEBUG || Printer.err)Printer.err("Clip is not auto closing!"+clip);
                // fail -> will try with SourceDataLine
                return false;
            }
            clip = (AutoClosingClip) line;
            clip.setAutoClosing(true);
            if (DEBUG || Printer.debug) clip.addLineListener(this);
        } catch (Exception e) {
            if (DEBUG || Printer.err)e.printStackTrace();
            // fail silently
            return false;
        }

        if (clip==null) {
            // fail silently
            return false;
        }

        if (DEBUG || Printer.debug)Printer.debug("Loaded clip.");
        return true;
    }
 
Example 14
Source File: JavaSoundAudioClip.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private boolean createClip() {

        if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createClip()");

        try {
            DataLine.Info info = new DataLine.Info(Clip.class, loadedAudioFormat);
            if (!(AudioSystem.isLineSupported(info)) ) {
                if (DEBUG || Printer.err)Printer.err("Clip not supported: "+loadedAudioFormat);
                // fail silently
                return false;
            }
            Object line = AudioSystem.getLine(info);
            if (!(line instanceof AutoClosingClip)) {
                if (DEBUG || Printer.err)Printer.err("Clip is not auto closing!"+clip);
                // fail -> will try with SourceDataLine
                return false;
            }
            clip = (AutoClosingClip) line;
            clip.setAutoClosing(true);
            if (DEBUG || Printer.debug) clip.addLineListener(this);
        } catch (Exception e) {
            if (DEBUG || Printer.err)e.printStackTrace();
            // fail silently
            return false;
        }

        if (clip==null) {
            // fail silently
            return false;
        }

        if (DEBUG || Printer.debug)Printer.debug("Loaded clip.");
        return true;
    }
 
Example 15
Source File: AlarmNotifier.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private void enableHorn () throws UnsupportedAudioFileException, IOException, LineUnavailableException
{
    if ( ( this.clip == null || !this.clip.isRunning () ) && Activator.getDefault ().getPreferenceStore ().getBoolean ( PreferenceConstants.BELL_ACTIVATED_KEY ) )
    {
        final AudioInputStream sound = AudioSystem.getAudioInputStream ( this.soundFile );
        final DataLine.Info info = new DataLine.Info ( Clip.class, sound.getFormat () );
        this.clip = (Clip)AudioSystem.getLine ( info );
        this.clip.open ( sound );
        this.clip.loop ( Clip.LOOP_CONTINUOUSLY );
    }
    if ( !this.bellIcon.isDisposed () )
    {
        this.bellIcon.setImage ( getBellIcon () );
    }
}
 
Example 16
Source File: JavaSoundAudioClip.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private boolean createClip() {

        if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip.createClip()");

        try {
            DataLine.Info info = new DataLine.Info(Clip.class, loadedAudioFormat);
            if (!(AudioSystem.isLineSupported(info)) ) {
                if (DEBUG || Printer.err)Printer.err("Clip not supported: "+loadedAudioFormat);
                // fail silently
                return false;
            }
            Object line = AudioSystem.getLine(info);
            if (!(line instanceof AutoClosingClip)) {
                if (DEBUG || Printer.err)Printer.err("Clip is not auto closing!"+clip);
                // fail -> will try with SourceDataLine
                return false;
            }
            clip = (AutoClosingClip) line;
            clip.setAutoClosing(true);
            if (DEBUG || Printer.debug) clip.addLineListener(this);
        } catch (Exception e) {
            if (DEBUG || Printer.err)e.printStackTrace();
            // fail silently
            return false;
        }

        if (clip==null) {
            // fail silently
            return false;
        }

        if (DEBUG || Printer.debug)Printer.debug("Loaded clip.");
        return true;
    }
 
Example 17
Source File: AvoidStandbyModeService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
private SourceDataLine getSourceDataLine(AudioFormat audioFormat) throws LineUnavailableException {
    DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
    return (SourceDataLine) AudioSystem.getLine(dataLineInfo);
}
 
Example 18
Source File: DefaultMixers.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static boolean testMixer(Mixer mixer, Class lineType,
                                 String providerClassName,
                                 String instanceName) {
    boolean allOk = true;

    try {
        String propertyValue = (providerClassName != null) ? providerClassName: "" ;
        propertyValue += "#" + instanceName;
        out("property value: " + propertyValue);
        System.setProperty(lineType.getName(), propertyValue);
        Line line = null;
        Line.Info info = null;
        Line.Info[] infos;
        AudioFormat format = null;
        if (lineType == SourceDataLine.class || lineType == Clip.class) {
            infos = mixer.getSourceLineInfo();
            format = getFirstLinearFormat(infos);
            info = new DataLine.Info(lineType, format);
        } else if (lineType == TargetDataLine.class) {
            infos = mixer.getTargetLineInfo();
            format = getFirstLinearFormat(infos);
            info = new DataLine.Info(lineType, format);
        } else if (lineType == Port.class) {
            /* Actually, a Ports Mixer commonly has source infos
               as well as target infos. We ignore this here, since we
               just need a random one. */
            infos = mixer.getSourceLineInfo();
            for (int i = 0; i < infos.length; i++) {
                if (infos[i] instanceof Port.Info) {
                    info = infos[i];
                    break;
                }
            }
        }
        out("Line.Info: " + info);
        line = AudioSystem.getLine(info);
        out("line: " + line);
        if (! lineType.isInstance(line)) {
            out("type " + lineType + " failed: class should be '" +
                lineType + "' but is '" + line.getClass() + "'!");
            allOk = false;
        }
    } catch (Exception e) {
        out("Exception thrown; Test NOT failed.");
        e.printStackTrace();
    }
    return allOk;
}
 
Example 19
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 20
Source File: DavidSFXModule.java    From mochadoom with GNU General Public License v3.0 4 votes vote down vote up
/** This one will only create datalines for common clip/audioline samples
 *  directly.
 * 
 * @param c
 * @param sfxid
 */
private final void  createDataLineForChannel(int c, int sfxid){
	
	// None? Make a new one.
	
	if (channels[c].auline == null) {
       	try {
       		DoomSound tmp=cachedSounds.get(sfxid);
       		// Sorry, Charlie. Gotta make a new one.
       		DataLine.Info info = new DataLine.Info(SourceDataLine.class, DoomSound.DEFAULT_SAMPLES_FORMAT);
			channels[c].auline = (SourceDataLine) AudioSystem.getLine(info);
			channels[c].auline.open(tmp.format);
		} catch (LineUnavailableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				boolean errors=false;
       			// Add individual volume control.
       			if (channels[c].auline.isControlSupported(Type.MASTER_GAIN))
       				channels[c].vc=(FloatControl) channels[c].auline
       				.getControl(Type.MASTER_GAIN);
       			else {
       			System.err.print("MASTER_GAIN, ");
       			errors=true;
       			if (channels[c].auline.isControlSupported(Type.VOLUME))
           				channels[c].vc=(FloatControl) channels[c].auline
           				.getControl(Type.VOLUME);
       			else 
       				System.err.print("VOLUME, ");
       			} 
       			

       			// Add individual pitch control.
       			if (channels[c].auline.isControlSupported(Type.SAMPLE_RATE)){
       				channels[c].pc=(FloatControl) channels[c].auline
       				.getControl(Type.SAMPLE_RATE);
       			} else {
       				errors=true;
       				System.err.print("SAMPLE_RATE, ");
       			} 
       			
       			// Add individual pan control
       			if (channels[c].auline.isControlSupported(Type.BALANCE)){
       				channels[c].bc=(FloatControl) channels[c].auline
       				.getControl(FloatControl.Type.BALANCE);
       			} else {
       				System.err.print("BALANCE, ");
       				errors=true;
       				if (channels[c].auline.isControlSupported(Type.PAN)){        					
       				channels[c].bc=(FloatControl) channels[c].auline
       				.getControl(FloatControl.Type.PAN);
       			} else {
       				System.err.print("PANNING ");
       				}
       			}

       			if (errors) System.err.printf("for channel %d NOT supported!\n",c);
       			
       			channels[c].auline.start();
       		}
}