javax.sound.sampled.Clip#start ( )源码实例Demo

下面列出了javax.sound.sampled.Clip#start ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Azzet   文件: TestAudio.java
private void doTest() throws AssetException, InterruptedException
{
	Clip clip = Assets.load("cowbell.wav");

	assertNotNull( clip );
	
	clip.start();

	Thread.sleep(1000);
	
	clip.stop();
	clip.close();
}
 
源代码2 项目: AML-Project   文件: Audio.java
private static void play(String file)
{
	File f = new File(file);
	if(f.canRead())
	{
		try
		{
			Clip clip = AudioSystem.getClip();
			AudioInputStream inputStream = AudioSystem.getAudioInputStream(f);
			clip.open(inputStream);
			clip.start();
		}
		catch(Exception e)
		{
			//Do nothing
		}
	}
}
 
源代码3 项目: txtUML   文件: UI.java
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();
	}
}
 
源代码4 项目: openjdk-jdk9   文件: IsRunningHang.java
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();
}
 
源代码5 项目: opsu   文件: MultiClip.java
/**
 * Plays the clip with the specified volume.
 * @param volume the volume the play at
 * @param listener the line listener
 * @throws LineUnavailableException if a clip object is not available or
 *         if the line cannot be opened due to resource restrictions
 */
public void start(float volume, LineListener listener) throws LineUnavailableException {
	Clip clip = getClip();
	if (clip == null)
		return;

	// PulseAudio does not support Master Gain
	if (clip.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
		// set volume
		FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
		float dB = (float) (Math.log(volume) / Math.log(10.0) * 20.0);
		gainControl.setValue(Utils.clamp(dB, gainControl.getMinimum(), gainControl.getMaximum()));
	} else if (clip.isControlSupported(FloatControl.Type.VOLUME)) {
		// The docs don't mention what unit "volume" is supposed to be,
		// but for PulseAudio it seems to be amplitude
		FloatControl volumeControl = (FloatControl) clip.getControl(FloatControl.Type.VOLUME);
		float amplitude = (float) Math.sqrt(volume) * volumeControl.getMaximum();
		volumeControl.setValue(Utils.clamp(amplitude, volumeControl.getMinimum(), volumeControl.getMaximum()));
	}

	if (listener != null)
		clip.addLineListener(listener);
	clip.setFramePosition(0);
	clip.start();
}
 
源代码6 项目: openjdk-jdk9   文件: ChangingBuffer.java
private static boolean doMixerClip(Mixer mixer, AudioFormat format) {
    if (mixer==null) return false;
    try {
        System.out.println("Trying mixer "+mixer+":");
            DataLine.Info info = new DataLine.Info(
                                      Clip.class,
                                      format,
                                      (int) samplerate);

            Clip clip = (Clip) mixer.getLine(info);
        System.out.println("  - got clip: "+clip);
        System.out.println("  - open with format "+format);
        clip.open(format, buffer, 0, buffer.length);
        System.out.println("  - playing...");
        clip.start();
        System.out.println("  - waiting while it's active...");
        while (clip.isActive())
                Thread.sleep(100);
        System.out.println("  - waiting 100millis");
        Thread.sleep(100);
        System.out.println("  - drain1");
        clip.drain();
        System.out.println("  - drain2");
        clip.drain();
        System.out.println("  - stop");
        clip.stop();
        System.out.println("  - close");
        clip.close();
        System.out.println("  - closed");
    } catch (Throwable t) {
        System.out.println("  - Caught exception. Not failed.");
        System.out.println("  - "+t.toString());
        return false;
    }
    return true;
}
 
源代码7 项目: opsu-dance   文件: MultiClip.java
/**
 * Plays the clip with the specified volume.
 * @param volume the volume the play at
 * @param listener the line listener
 * @throws LineUnavailableException if a clip object is not available or
 *         if the line cannot be opened due to resource restrictions
 */
public void start(float volume, LineListener listener) throws LineUnavailableException {
	Clip clip = getClip();
	if (clip == null)
		return;

	// PulseAudio does not support Master Gain
	if (clip.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
		// set volume
		FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
		float dB = (float) (Math.log(volume) / Math.log(10.0) * 20.0);
		gainControl.setValue(dB);
	}

	if (listener != null)
		clip.addLineListener(listener);
	clip.setFramePosition(0);
	clip.start();
}
 
源代码8 项目: javagame   文件: WaveEngine.java
/**
 * ��
 * @param name �o�^��
 */
public void play(String name) {
    // ���O�ɑΉ�����N���b�v���擾
    Clip clip = (Clip)clipMap.get(name);
    if (clip != null) {
        clip.start();
    }
}
 
源代码9 项目: Game   文件: soundPlayer.java
public static void playSoundFile(String key) {
	try {
		if (!mudclient.optionSoundDisabled) {
			File sound = mudclient.soundCache.get(key + ".wav");
			if (sound == null)
				return;
			try {
				// PC sound code:
				final Clip clip = AudioSystem.getClip();
				clip.addLineListener(myLineEvent -> {
					if (myLineEvent.getType() == LineEvent.Type.STOP)
						clip.close();
				});
				clip.open(AudioSystem.getAudioInputStream(sound));
				clip.start();

				// Android sound code:
				//int dataLength = DataOperations.getDataFileLength(key + ".pcm", soundData);
				//int offset = DataOperations.getDataFileOffset(key + ".pcm", soundData);
				//clientPort.playSound(soundData, offset, dataLength);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	} catch (RuntimeException var6) {
		throw GenUtil.makeThrowable(var6, "client.SC(" + "dummy" + ',' + (key != null ? "{...}" : "null") + ')');
	}
}
 
源代码10 项目: openjdk-jdk9   文件: ClipDrain.java
private static void doMixerClip(Mixer mixer) throws Exception {
    boolean waitedEnough=false;
    try {
        DataLine.Info info = new DataLine.Info(Clip.class, format);
        Clip clip = (Clip) mixer.getLine(info);
        clip.open(format, soundData, 0, soundData.length);

        // sanity
        if (clip.getMicrosecondLength()/1000 < 9900) {
            throw new Exception("clip's microsecond length should be at least 9900000, but it is "+clip.getMicrosecondLength());
        }
        long start = System.currentTimeMillis();

        System.out.println(" ---------- start --------");
        clip.start();
        // give time to actually start it. ALSA implementation needs that...
        Thread.sleep(300);
        System.out.println("drain ... ");
        clip.drain();
        long elapsedTime = System.currentTimeMillis() - start;
        System.out.println("close ... ");
        clip.close();
        System.out.println("... done");
        System.out.println("Playback duration: "+elapsedTime+" milliseconds.");
        waitedEnough = elapsedTime >= ((clip.getMicrosecondLength() / 1000) - TOLERANCE_MS);
    } catch (Throwable t) {
            System.out.println("  - Caught exception. Not failed.");
            System.out.println("  - "+t.toString());
            return;
    }
    if (!waitedEnough) {
        throw new Exception("Drain did not wait long enough to play entire clip.");
    }
    successfulTests++;
}
 
源代码11 项目: openjdk-jdk9   文件: ClipLinuxCrash2.java
public long 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("  Test program: preparing to play back "+len+" bytes == "+bytes2Ms(len, format)+"ms audio...");

    byte[] fakedata=new byte[len];
    InputStream is = new ByteArrayInputStream(fakedata);
    AudioInputStream ais = new AudioInputStream(is, format, fakedata.length/format.getFrameSize());

    DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat());
    clip = (Clip) AudioSystem.getLine(info);
    clip.addLineListener(this);

    out("  Test program: opening clip="+((clip==null)?"null":clip.toString()));
    clip.open(ais);
    ais.close();
    out("  Test program: starting clip="+((clip==null)?"null":clip.toString()));
    clip.start();
    return bytes2Ms(fakedata.length, format);
}
 
源代码12 项目: javagame   文件: WaveEngine.java
/**
 * ��
 * @param name �o�^��
 */
public void play(String name) {
    // ���O�ɑΉ�����N���b�v���擾
    Clip clip = (Clip)clipMap.get(name);
    if (clip != null) {
        clip.start();
    }
}
 
源代码13 项目: javagame   文件: WaveEngine.java
/**
 * ��
 * @param name �o�^��
 */
public void play(String name) {
    // ���O�ɑΉ�����N���b�v���擾
    Clip clip = (Clip)clipMap.get(name);
    if (clip != null) {
        clip.start();
    }
}
 
源代码14 项目: FxDock   文件: ClipPlayer.java
public static void play(InputStream in)
{
	try
	{
		AudioInputStream stream = AudioSystem.getAudioInputStream(in);
		AudioFormat format = stream.getFormat();
		DataLine.Info info = new DataLine.Info(Clip.class, format);
		
		final Clip clip = (Clip)AudioSystem.getLine(info);
		clip.addLineListener(new LineListener()
		{
			public void update(LineEvent ev)
			{
				LineEvent.Type t = ev.getType();
				if(t == LineEvent.Type.STOP)
				{
					clip.close();
				}
			}
		});
		clip.open(stream);
		clip.start();
	}
	catch(Exception e)
	{
		Log.err(e);
	}
}
 
源代码15 项目: mars-sim   文件: TelegraphSound.java
/**
 * This method allows to actually play the sound provided from the
 * {@link #audioInputStream}
 * 
 * @throws LineUnavailableException
 *             if the {@link Clip} object can't be created
 * @throws IOException
 *             if the audio file can't be find
 */
protected void play() throws LineUnavailableException, IOException {
	final Clip clip = AudioSystem.getClip();
	clip.addLineListener(listener);
	clip.open(audioInputStream);
	try {
		clip.start();
		listener.waitUntilDone();
	} catch (final InterruptedException e) {
		e.printStackTrace();
	} finally {
		clip.close();
	}
	audioInputStream.close();
}
 
源代码16 项目: ev3dev-lang-java   文件: Sound.java
/**
 * Play a wav file. Must be mono, from 8kHz to 48kHz, and 8-bit or 16-bit.
 *
 * @param file the 8-bit or 16-bit PWM (WAV) sample file
 */
public void playSample(final File file) {
    try (AudioInputStream audioIn = AudioSystem.getAudioInputStream(file.toURI().toURL())) {

        Clip clip = AudioSystem.getClip();
        clip.open(audioIn);
        clip.start();
        Delay.usDelay(clip.getMicrosecondLength());
        clip.close();

    } catch (IOException | LineUnavailableException | UnsupportedAudioFileException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
        throw new RuntimeException(e);
    }
}
 
源代码17 项目: WorldGrower   文件: Sound.java
public void play() {
	try {
		final Clip clipToPlay;
		if (preLoadedClip != null) {
			clipToPlay = preLoadedClip;
			clipToPlay.setFramePosition(0);
		} else {
			clipToPlay = openClip(CLOSE_AFTER_PLAYING);
		}
		clipToPlay.start();

	} catch (IOException | LineUnavailableException | UnsupportedAudioFileException e) {
		throw new IllegalStateException(e);
	}
}
 
源代码18 项目: javagame   文件: WaveEngine.java
/**
 * ��
 * @param name �o�^��
 */
public void play(String name) {
    // ���O�ɑΉ�����N���b�v���擾
    Clip clip = clipMap.get(name);
    if (clip != null) {
        clip.start();
    }
}
 
源代码19 项目: txtUML   文件: GUI.java
private void playSound(String soundName) {
	try {
		AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
		AudioFormat format = audioInputStream.getFormat();
		DataLine.Info info = new DataLine.Info(Clip.class, format);
		Clip clip = (Clip) AudioSystem.getLine(info);
		clip.open(audioInputStream);
		clip.start();
	} catch (IllegalArgumentException | IOException | LineUnavailableException | UnsupportedAudioFileException e) {
		e.printStackTrace();
	}
}
 
源代码20 项目: openjdk-jdk9   文件: bug6251460.java
static protected void test()
        throws LineUnavailableException, InterruptedException {
    DataLine.Info info = new DataLine.Info(Clip.class, format);
    Clip clip = (Clip)AudioSystem.getLine(info);
    final MutableBoolean clipStoppedEvent = new MutableBoolean(false);
    clip.addLineListener(new LineListener() {
        @Override
        public void update(LineEvent event) {
            if (event.getType() == LineEvent.Type.STOP) {
                synchronized (clipStoppedEvent) {
                    clipStoppedEvent.value = true;
                    clipStoppedEvent.notifyAll();
                }
            }
        }
    });
    clip.open(format, soundData, 0, soundData.length);

    long lengthClip = clip.getMicrosecondLength() / 1000;
    log("Clip length " + lengthClip + " ms");
    log("Playing...");
    for (int i=1; i<=LOOP_COUNT; i++) {
        long startTime = currentTimeMillis();
        log(" Loop " + i);
        clip.start();

        synchronized (clipStoppedEvent) {
            while (!clipStoppedEvent.value) {
                clipStoppedEvent.wait();
            }
            clipStoppedEvent.value = false;
        }

        long endTime = currentTimeMillis();
        long lengthPlayed = endTime - startTime;

        if (lengthClip > lengthPlayed + 20) {
            log(" ERR: Looks like sound didn't play: played " + lengthPlayed + " ms instead " + lengthClip);
            countErrors++;
        } else {
            log(" OK: played " + lengthPlayed + " ms");
        }
        clip.setFramePosition(0);

    }
    log("Played " + LOOP_COUNT + " times, " + countErrors + " errors detected.");
}