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

The following examples show how to use javax.sound.sampled.AudioSystem#getClip() . 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: MetronomePlugin.java    From plugins with GNU General Public License v3.0 8 votes vote down vote up
private Clip GetAudioClip(String path)
{
	File audioFile = new File(path);
	if (!audioFile.exists())
	{
		return null;
	}

	try (AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile))
	{
		Clip audioClip = AudioSystem.getClip();
		audioClip.open(audioStream);
		FloatControl gainControl = (FloatControl) audioClip.getControl(FloatControl.Type.MASTER_GAIN);
		float gainValue = (((float) config.volume()) * 40f / 100f) - 35f;
		gainControl.setValue(gainValue);

		return audioClip;
	}
	catch (IOException | LineUnavailableException | UnsupportedAudioFileException e)
	{
		log.warn("Error opening audiostream from " + audioFile, e);
		return null;
	}
}
 
Example 2
Source File: OscilloscopeDispatcher.java    From nebula with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a clip from the passed sound file and plays it. If the clip
 * is currently playing then the method returns, get the clip with
 * {@link #getClip()} to control it.
 * 
 * @param file
 * @param loopCount
 */
public void playClip(File file, int loopCount) {

	if (file == null)
		return;

	try {

		if ((this.clip == null) || !file.getAbsolutePath().equals(this.oldFile)) {
			this.oldFile = file.getAbsolutePath();
			this.clip = AudioSystem.getClip();
			this.clip.open(AudioSystem.getAudioInputStream(file));
		}
		if (this.clip.isActive())
			return;
		// clip.stop(); << Alternative

		this.clip.setFramePosition(0);
		this.clip.loop(loopCount);

	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 3
Source File: Audio.java    From AML-Project with Apache License 2.0 6 votes vote down vote up
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
		}
	}
}
 
Example 4
Source File: BlorbSounds.java    From petscii-bbs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected boolean putToDatabase(final Chunk chunk, final int resnum) {

  final InputStream aiffStream =
    new  MemoryAccessInputStream(chunk.getMemoryAccess(), 0,
        chunk.getSize() + Chunk.CHUNK_HEADER_LENGTH);
  try {

    final AudioFileFormat aiffFormat =
      AudioSystem.getAudioFileFormat(aiffStream);
    final AudioInputStream stream = new AudioInputStream(aiffStream,
      aiffFormat.getFormat(), (long) chunk.getSize());
    final Clip clip = AudioSystem.getClip();
    clip.open(stream);      
    sounds.put(resnum, new DefaultSoundEffect(clip));
    return true;

  } catch (Exception ex) {

    ex.printStackTrace();
  }
  return false;
}
 
Example 5
Source File: SoundSystem.java    From Robot-Overlord-App with GNU General Public License v2.0 6 votes vote down vote up
static public void playSound(String url) {
	if (url.isEmpty()) return;

	try {
		Clip clip = AudioSystem.getClip();
		BufferedInputStream x = new BufferedInputStream(new FileInputStream(url));
		AudioInputStream inputStream = AudioSystem.getAudioInputStream(x);
		clip.open(inputStream);
		clip.start();
	} catch (Exception e) {
		e.printStackTrace();
		System.err.println(e.getMessage());
	}
}
 
Example 6
Source File: SoundNotifier.java    From MercuryTrade with MIT License 6 votes vote down vote up
private void play(String wavPath, float db) {
    if (!dnd && db > -40) {
        ClassLoader classLoader = getClass().getClassLoader();
        try (AudioInputStream stream = AudioSystem.getAudioInputStream(classLoader.getResource(wavPath))) {
            Clip clip = AudioSystem.getClip();
            clip.open(stream);
            if (db != 0.0) {
                FloatControl gainControl =
                        (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
                gainControl.setValue(db);
            }
            clip.start();
        } catch (Exception e) {
            logger.error("Cannot start playing wav file: ", e);
        }
    }
}
 
Example 7
Source File: AudioFormat.java    From Azzet with Open Software License 3.0 5 votes vote down vote up
@Override
public Clip loadAsset( InputStream input, AssetInfo assetInfo ) throws Exception
{
	AudioInputStream ais = AudioSystem.getAudioInputStream( input );
	Clip clip = AudioSystem.getClip();
	clip.open( ais );
	return clip;
}
 
Example 8
Source File: Demo_MultichannelAudio_NativeMultipleSoundcard.java    From haxademic with MIT License 5 votes vote down vote up
protected Clip clipFromMixer() {
	try {
		int mixerIndex = UI.valueInt(MIXER_INDEX);
		mixerIndex = P.constrain(mixerIndex, 0, mixers.size() - 1);
		Clip clip;
		clip = AudioSystem.getClip(mixers.get(mixerIndex).getMixerInfo());
		return clip;
	} catch (LineUnavailableException e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 9
Source File: Sound.java    From ev3dev-lang-java with MIT License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 10
Source File: TelegraphSound.java    From mars-sim with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 11
Source File: Notifier.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private synchronized void playCustomSound()
{
	long currentMTime = NOTIFICATION_FILE.exists() ? NOTIFICATION_FILE.lastModified() : CLIP_MTIME_BUILTIN;
	if (clip == null || currentMTime != lastClipMTime || !clip.isOpen())
	{
		if (clip != null)
		{
			clip.close();
		}

		try
		{
			clip = AudioSystem.getClip();
		}
		catch (LineUnavailableException e)
		{
			lastClipMTime = CLIP_MTIME_UNLOADED;
			log.warn("Unable to play notification", e);
			Toolkit.getDefaultToolkit().beep();
			return;
		}

		lastClipMTime = currentMTime;

		if (!tryLoadNotification())
		{
			Toolkit.getDefaultToolkit().beep();
			return;
		}
	}

	// Using loop instead of start + setFramePosition prevents a the clip
	// from not being played sometimes, presumably a race condition in the
	// underlying line driver
	clip.loop(1);
}
 
Example 12
Source File: soundPlayer.java    From Game with GNU General Public License v3.0 5 votes vote down vote up
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") + ')');
	}
}
 
Example 13
Source File: OscilloscopeDispatcher.java    From nebula with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a clip from the passed sound file and plays it. If the clip
 * is currently playing then the method returns, get the clip with
 * {@link #getClip()} to control it.
 * 
 * @param file
 * @param loopCount
 */
public void playClip(File file, int loopCount) {

	if (file == null) {
		return;
	}

	try {

		if ((this.clip == null)
				|| !file.getAbsolutePath().equals(this.oldFile)) {
			this.oldFile = file.getAbsolutePath();
			this.clip = AudioSystem.getClip();
			this.clip.open(AudioSystem.getAudioInputStream(file));
		}
		if (this.clip.isActive()) {
			return;
		}
		// clip.stop(); << Alternative

		this.clip.setFramePosition(0);
		this.clip.loop(loopCount);

	} catch (Exception e) {
		// swallow
	}
}
 
Example 14
Source File: Resource.java    From salty-engine with Apache License 2.0 5 votes vote down vote up
static Clip createClip(final AudioInputStream inputStream) {
    Clip clip = null;
    try {
        clip = AudioSystem.getClip();
        clip.open(inputStream);
    } catch (final LineUnavailableException | IOException e) {
        e.printStackTrace();
    }

    return clip;
}
 
Example 15
Source File: SoundController.java    From opsu-dance with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Loads and returns a Clip from an audio input stream.
 * @param ref the resource name
 * @param audioIn the audio input stream
 * @param isMP3 true if MP3, false if WAV
 * @return the loaded and opened clip
 */
private static MultiClip loadClip(String ref, AudioInputStream audioIn, boolean isMP3)
		throws IOException, LineUnavailableException {
	AudioFormat format = audioIn.getFormat();
	if (isMP3) {
		AudioFormat decodedFormat = new AudioFormat(
				AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16,
				format.getChannels(), format.getChannels() * 2, format.getSampleRate(), false);
		AudioInputStream decodedAudioIn = AudioSystem.getAudioInputStream(decodedFormat, audioIn);
		format = decodedFormat;
		audioIn = decodedAudioIn;
	}
	DataLine.Info info = new DataLine.Info(Clip.class, format);
	if (AudioSystem.isLineSupported(info))
		return new MultiClip(ref, audioIn);

	// try to find closest matching line
	Clip clip = AudioSystem.getClip();
	AudioFormat[] formats = ((DataLine.Info) clip.getLineInfo()).getFormats();
	int bestIndex = -1;
	float bestScore = 0;
	float sampleRate = format.getSampleRate();
	if (sampleRate < 0)
		sampleRate = clip.getFormat().getSampleRate();
	float oldSampleRate = sampleRate;
	while (true) {
		for (int i = 0; i < formats.length; i++) {
			AudioFormat curFormat = formats[i];
			AudioFormat newFormat = new AudioFormat(
					sampleRate, curFormat.getSampleSizeInBits(),
					curFormat.getChannels(), true, curFormat.isBigEndian());
			formats[i] = newFormat;
			DataLine.Info newLine = new DataLine.Info(Clip.class, newFormat);
			if (AudioSystem.isLineSupported(newLine) &&
			    AudioSystem.isConversionSupported(newFormat, format)) {
				float score = 1
						+ (newFormat.getSampleRate() == sampleRate ? 5 : 0)
						+ (newFormat.getSampleSizeInBits() == format.getSampleSizeInBits() ? 5 : 0)
						+ (newFormat.getChannels() == format.getChannels() ? 5 : 0)
						+ (newFormat.isBigEndian() == format.isBigEndian() ? 1 : 0)
						+ newFormat.getSampleRate() / 11025
						+ newFormat.getChannels()
						+ newFormat.getSampleSizeInBits() / 8;
				if (score > bestScore) {
					bestIndex = i;
					bestScore = score;
				}
			}
		}
		if (bestIndex < 0) {
			if (oldSampleRate < 44100) {
				if (sampleRate > 44100)
					break;
				sampleRate *= 2;
			} else {
				if (sampleRate < 44100)
					break;
				sampleRate /= 2;
			}
		} else
			break;
	}
	if (bestIndex >= 0)
		return new MultiClip(ref, AudioSystem.getAudioInputStream(formats[bestIndex], audioIn));

	// still couldn't find anything, try the default clip format
	return new MultiClip(ref, AudioSystem.getAudioInputStream(clip.getFormat(), audioIn));
}
 
Example 16
Source File: SoundController.java    From opsu with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Loads and returns a Clip from an audio input stream.
 * @param ref the resource name
 * @param audioIn the audio input stream
 * @return the loaded and opened clip
 */
private static MultiClip loadClip(String ref, AudioInputStream audioIn)
	throws IOException, LineUnavailableException {
	AudioFormat format = audioIn.getFormat();
	String encoding = format.getEncoding().toString();
	if (encoding.startsWith("MPEG")) {
		// decode MP3
		AudioFormat decodedFormat = new AudioFormat(
				AudioFormat.Encoding.PCM_SIGNED, format.getSampleRate(), 16,
				format.getChannels(), format.getChannels() * 2, format.getSampleRate(), false);
		AudioInputStream decodedAudioIn = AudioSystem.getAudioInputStream(decodedFormat, audioIn);
		format = decodedFormat;
		audioIn = decodedAudioIn;
	} else if (encoding.startsWith("GSM")) {
		// Currently there's no way to decode GSM in WAV containers in Java.
		// http://www.jsresources.org/faq_audio.html#gsm_in_wav
		Log.warn(
			"Failed to load audio file.\n" +
			"Java cannot decode GSM in WAV containers; " +
			"please re-encode this file to PCM format or remove it:\n" + ref
		);
		return null;
	}
	DataLine.Info info = new DataLine.Info(Clip.class, format);
	if (AudioSystem.isLineSupported(info))
		return new MultiClip(ref, audioIn);

	// try to find closest matching line
	Clip clip = AudioSystem.getClip();
	AudioFormat[] formats = ((DataLine.Info) clip.getLineInfo()).getFormats();
	int bestIndex = -1;
	float bestScore = 0;
	float sampleRate = format.getSampleRate();
	if (sampleRate < 0)
		sampleRate = clip.getFormat().getSampleRate();
	float oldSampleRate = sampleRate;
	while (true) {
		for (int i = 0; i < formats.length; i++) {
			AudioFormat curFormat = formats[i];
			AudioFormat newFormat = new AudioFormat(
					sampleRate, curFormat.getSampleSizeInBits(),
					curFormat.getChannels(), true, curFormat.isBigEndian());
			formats[i] = newFormat;
			DataLine.Info newLine = new DataLine.Info(Clip.class, newFormat);
			if (AudioSystem.isLineSupported(newLine) &&
			    AudioSystem.isConversionSupported(newFormat, format)) {
				float score = 1
						+ (newFormat.getSampleRate() == sampleRate ? 5 : 0)
						+ (newFormat.getSampleSizeInBits() == format.getSampleSizeInBits() ? 5 : 0)
						+ (newFormat.getChannels() == format.getChannels() ? 5 : 0)
						+ (newFormat.isBigEndian() == format.isBigEndian() ? 1 : 0)
						+ newFormat.getSampleRate() / 11025
						+ newFormat.getChannels()
						+ newFormat.getSampleSizeInBits() / 8;
				if (score > bestScore) {
					bestIndex = i;
					bestScore = score;
				}
			}
		}
		if (bestIndex < 0) {
			if (oldSampleRate < 44100) {
				if (sampleRate > 44100)
					break;
				sampleRate *= 2;
			} else {
				if (sampleRate < 44100)
					break;
				sampleRate /= 2;
			}
		} else
			break;
	}
	if (bestIndex >= 0)
		return new MultiClip(ref, AudioSystem.getAudioInputStream(formats[bestIndex], audioIn));

	// still couldn't find anything, try the default clip format
	return new MultiClip(ref, AudioSystem.getAudioInputStream(clip.getFormat(), audioIn));
}
 
Example 17
Source File: SoundPlayer.java    From ShootPlane with Apache License 2.0 4 votes vote down vote up
public SoundPlayer(String filePath) throws LineUnavailableException, UnsupportedAudioFileException, IOException {
File file = new File(filePath);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
clip = AudioSystem.getClip();
clip.open(audioInputStream);
   }