javax.sound.sampled.AudioSystem Java Examples
The following examples show how to use
javax.sound.sampled.AudioSystem.
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 |
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: JavaSoundAudioClip.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
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: PCM_FLOAT_support.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { // 1st checks Encoding.PCM_FLOAT is available pcmFloatEnc = Encoding.PCM_FLOAT; Encoding[] encodings = AudioSystem.getTargetEncodings(pcmFloatEnc); out("conversion from PCM_FLOAT to " + encodings.length + " encodings:"); for (Encoding e: encodings) { out(" - " + e); } if (encodings.length == 0) { testFailed = true; } test(Encoding.PCM_SIGNED); test(Encoding.PCM_UNSIGNED); if (testFailed) { throw new Exception("test failed"); } out("test passed."); }
Example #4
Source File: Demo_MultichannelAudio_NativeMultipleSoundcard.java From haxademic with MIT License | 6 votes |
public void play(File file, Clip clip) { try { // get a mixer and play clip like that clip.addLineListener(new LineListener() { @Override public void update(LineEvent event) { if (event.getType() == LineEvent.Type.STOP) { clip.close(); } } }); clip.open(AudioSystem.getAudioInputStream(file)); clip.start(); } catch (Exception exc) { exc.printStackTrace(System.out); } }
Example #5
Source File: DataLine_ArrayIndexOutOfBounds.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { Mixer.Info[] infos = AudioSystem.getMixerInfo(); log("" + infos.length + " mixers detected"); for (int i=0; i<infos.length; i++) { Mixer mixer = AudioSystem.getMixer(infos[i]); log("Mixer " + (i+1) + ": " + infos[i]); try { mixer.open(); for (Scenario scenario: scenarios) { testSDL(mixer, scenario); testTDL(mixer, scenario); } mixer.close(); } catch (LineUnavailableException ex) { log("LineUnavailableException: " + ex); } } if (failed == 0) { log("PASSED (" + total + " tests)"); } else { log("FAILED (" + failed + " of " + total + " tests)"); throw new Exception("Test FAILED"); } }
Example #6
Source File: VoicePlay.java From oim-fx with MIT License | 6 votes |
public VoicePlay() { try { format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0f, 16, 1, 2, 44100.0f, false); DataLine.Info listenInfo = new DataLine.Info(TargetDataLine.class, format); boolean l = AudioSystem.isLineSupported(listenInfo); if (l) { listenLine = (TargetDataLine) AudioSystem.getLine(listenInfo); } DataLine.Info playInfo = new DataLine.Info(SourceDataLine.class, format); boolean p = AudioSystem.isLineSupported(listenInfo); if (p) { playLine = (SourceDataLine) AudioSystem.getLine(playInfo); } lineSupported = l && p; } catch (LineUnavailableException e) { e.printStackTrace(); } }
Example #7
Source File: WaveEngine.java From javagame with MIT License | 6 votes |
/** * 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 #8
Source File: StdAudio.java From algs4 with GNU General Public License v3.0 | 6 votes |
private static void init() { try { // 44,100 Hz, 16-bit audio, mono, signed PCM, little endian AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, MONO, SIGNED, LITTLE_ENDIAN); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); line = (SourceDataLine) AudioSystem.getLine(info); line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE); // the internal buffer is a fraction of the actual buffer size, this choice is arbitrary // it gets divided because we can't expect the buffered data to line up exactly with when // the sound card decides to push out its samples. buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE/3]; } catch (LineUnavailableException e) { System.out.println(e.getMessage()); } // no sound gets made before this call line.start(); }
Example #9
Source File: AudioFileSoundbankReader.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
public Soundbank getSoundbank(File file) throws InvalidMidiDataException, IOException { try { AudioInputStream ais = AudioSystem.getAudioInputStream(file); ais.close(); ModelByteBufferWavetable osc = new ModelByteBufferWavetable( new ModelByteBuffer(file, 0, file.length()), -4800); ModelPerformer performer = new ModelPerformer(); performer.getOscillators().add(osc); SimpleSoundbank sbk = new SimpleSoundbank(); SimpleInstrument ins = new SimpleInstrument(); ins.add(performer); sbk.addInstrument(ins); return sbk; } catch (UnsupportedAudioFileException e1) { return null; } catch (IOException e) { return null; } }
Example #10
Source File: WaveFileWriter.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException { //$$fb the following check must come first ! Otherwise // the next frame length check may throw an IOException and // interrupt iterating File Writers. (see bug 4351296) // throws IllegalArgumentException if not supported WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream); //$$fb when we got this far, we are committed to write this file // we must know the total data length to calculate the file length if( stream.getFrameLength() == AudioSystem.NOT_SPECIFIED ) { throw new IOException("stream length not specified"); } int bytesWritten = writeWaveFile(stream, waveFileFormat, out); return bytesWritten; }
Example #11
Source File: SoundTools.java From MyBox with Apache License 2.0 | 6 votes |
public void setGain(float ctrl) { try { Mixer.Info[] infos = AudioSystem.getMixerInfo(); for (Mixer.Info info : infos) { Mixer mixer = AudioSystem.getMixer(info); if (mixer.isLineSupported(Port.Info.SPEAKER)) { try ( Port port = (Port) mixer.getLine(Port.Info.SPEAKER)) { port.open(); if (port.isControlSupported(FloatControl.Type.VOLUME)) { FloatControl volume = (FloatControl) port.getControl(FloatControl.Type.VOLUME); volume.setValue(ctrl); } } } } } catch (Exception e) { } }
Example #12
Source File: PCM_FLOAT_support.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { // 1st checks Encoding.PCM_FLOAT is available pcmFloatEnc = Encoding.PCM_FLOAT; Encoding[] encodings = AudioSystem.getTargetEncodings(pcmFloatEnc); out("conversion from PCM_FLOAT to " + encodings.length + " encodings:"); for (Encoding e: encodings) { out(" - " + e); } if (encodings.length == 0) { testFailed = true; } test(Encoding.PCM_SIGNED); test(Encoding.PCM_UNSIGNED); if (testFailed) { throw new Exception("test failed"); } out("test passed."); }
Example #13
Source File: DataLine_ArrayIndexOutOfBounds.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { Mixer.Info[] infos = AudioSystem.getMixerInfo(); log("" + infos.length + " mixers detected"); for (int i=0; i<infos.length; i++) { Mixer mixer = AudioSystem.getMixer(infos[i]); log("Mixer " + (i+1) + ": " + infos[i]); try { mixer.open(); for (Scenario scenario: scenarios) { testSDL(mixer, scenario); testTDL(mixer, scenario); } mixer.close(); } catch (LineUnavailableException ex) { log("LineUnavailableException: " + ex); } } if (failed == 0) { log("PASSED (" + total + " tests)"); } else { log("FAILED (" + failed + " of " + total + " tests)"); throw new Exception("Test FAILED"); } }
Example #14
Source File: AutoCloseTimeCheck.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
public static void main(final String[] args) throws Exception { // Prepare the audio file File file = new File("audio.wav"); try { AudioFormat format = new AudioFormat(PCM_SIGNED, 44100, 8, 1, 1, 44100, false); AudioSystem.write(getStream(format), Type.WAVE, file); } catch (final Exception ignored) { return; // the test is not applicable } try { testSmallDelay(file); testBigDelay(file); } finally { Files.delete(file.toPath()); } }
Example #15
Source File: AudioFileSoundbankReader.java From tuxguitar with GNU Lesser General Public License v2.1 | 6 votes |
public Soundbank getSoundbank(File file) throws InvalidMidiDataException, IOException { try { AudioInputStream ais = AudioSystem.getAudioInputStream(file); ais.close(); ModelByteBufferWavetable osc = new ModelByteBufferWavetable( new ModelByteBuffer(file, 0, file.length()), -4800); ModelPerformer performer = new ModelPerformer(); performer.getOscillators().add(osc); SimpleSoundbank sbk = new SimpleSoundbank(); SimpleInstrument ins = new SimpleInstrument(); ins.add(performer); sbk.addInstrument(ins); return sbk; } catch (UnsupportedAudioFileException e1) { return null; } catch (IOException e) { return null; } }
Example #16
Source File: PCM_FLOAT_support.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { // 1st checks Encoding.PCM_FLOAT is available pcmFloatEnc = Encoding.PCM_FLOAT; Encoding[] encodings = AudioSystem.getTargetEncodings(pcmFloatEnc); out("conversion from PCM_FLOAT to " + encodings.length + " encodings:"); for (Encoding e: encodings) { out(" - " + e); } if (encodings.length == 0) { testFailed = true; } test(Encoding.PCM_SIGNED); test(Encoding.PCM_UNSIGNED); if (testFailed) { throw new Exception("test failed"); } out("test passed."); }
Example #17
Source File: AlawEncoderSync.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
@Override public void run() { log("ConversionThread[" + num + "] started."); try { InputStream inStream = new ByteArrayInputStream(pcmBuffer); AudioInputStream pcmStream = new AudioInputStream( inStream, pcmFormat, AudioSystem.NOT_SPECIFIED); AudioInputStream alawStream = AudioSystem.getAudioInputStream(alawFormat, pcmStream); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); int read = 0; byte[] data = new byte[4096]; while((read = alawStream.read(data)) != -1) { outStream.write(data, 0, read); } alawStream.close(); resultArray = outStream.toByteArray(); } catch (Exception ex) { log("ConversionThread[" + num + "] exception:"); log(ex); } log("ConversionThread[" + num + "] completed."); }
Example #18
Source File: AudioChatLine.java From The-5zig-Mod with GNU General Public License v3.0 | 5 votes |
private void loadClip() { clipLoaded = true; try { AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(The5zigMod.getModDirectory(), "media/" + The5zigMod.getDataManager().getUniqueId().toString() + "/" + ((ConversationChat) getMessage().getConversation()).getFriendUUID().toString() + "/" + getAudioData().getHash())); clip = (Clip) AudioSystem.getLine(new Line.Info(Clip.class)); clip.open(audioInputStream); } catch (Exception e) { e.printStackTrace(); } }
Example #19
Source File: AbstractDataLine.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
public final long getMicrosecondPosition() { long microseconds = getLongFramePosition(); if (microseconds != AudioSystem.NOT_SPECIFIED) { microseconds = Toolkit.frames2micros(getFormat(), microseconds); } return microseconds; }
Example #20
Source File: AppletMpegSPIWorkaround.java From jclic with GNU General Public License v2.0 | 5 votes |
public static AudioInputStream getAudioInputStream(AudioFormat targetFormat, AudioInputStream sourceStream) { try { return AudioSystem.getAudioInputStream(targetFormat, sourceStream); } catch (IllegalArgumentException iae) { if (DEBUG == true) { System.err.println("Using AppletMpegSPIWorkaround to get codec"); } try { Class.forName( "javazoom.spi.mpeg.sampled.convert.MpegFormatConversionProvider"); //"org.tritonus.sampled.convert.javalayer.MpegFormatConversionProvider"); return new javazoom.spi.mpeg.sampled.convert.MpegFormatConversionProvider(). //return new org.tritonus.sampled.convert.javalayer.MpegFormatConversionProvider(). getAudioInputStream(targetFormat, sourceStream); } catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException("Mpeg codec not properly installed"); } } }
Example #21
Source File: DirectAudioDevice.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
DirectAudioDevice(DirectAudioDeviceProvider.DirectAudioDeviceInfo portMixerInfo) { // pass in Line.Info, mixer, controls super(portMixerInfo, // Mixer.Info null, // Control[] null, // Line.Info[] sourceLineInfo null); // Line.Info[] targetLineInfo if (Printer.trace) Printer.trace(">> DirectAudioDevice: constructor"); // source lines DirectDLI srcLineInfo = createDataLineInfo(true); if (srcLineInfo != null) { sourceLineInfo = new Line.Info[2]; // SourcedataLine sourceLineInfo[0] = srcLineInfo; // Clip sourceLineInfo[1] = new DirectDLI(Clip.class, srcLineInfo.getFormats(), srcLineInfo.getHardwareFormats(), 32, // arbitrary minimum buffer size AudioSystem.NOT_SPECIFIED); } else { sourceLineInfo = new Line.Info[0]; } // TargetDataLine DataLine.Info dstLineInfo = createDataLineInfo(false); if (dstLineInfo != null) { targetLineInfo = new Line.Info[1]; targetLineInfo[0] = dstLineInfo; } else { targetLineInfo = new Line.Info[0]; } if (Printer.trace) Printer.trace("<< DirectAudioDevice: constructor completed"); }
Example #22
Source File: JavaSoundAudioClip.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
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 #23
Source File: SoundTools.java From MyBox with Apache License 2.0 | 5 votes |
public static synchronized Clip playback(AudioInputStream in, float addVolume) { try { AudioFormat baseFormat = in.getFormat(); AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); AudioInputStream ain = AudioSystem.getAudioInputStream(decodedFormat, in); DataLine.Info info = new DataLine.Info(Clip.class, decodedFormat); // https://stackoverflow.com/questions/25564980/java-use-a-clip-and-a-try-with-resources-block-which-results-with-no-sound final Clip clip = (Clip) AudioSystem.getLine(info); clip.open(ain); // Input stream must be closed, or else some thread is still running when application is exited. in.close(); ain.close(); FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(addVolume); // Add volume by decibels. return clip; } catch (Exception e) { logger.debug(e.toString()); return null; } }
Example #24
Source File: AiffFileWriter.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, OutputStream out) throws IOException { //$$fb the following check must come first ! Otherwise // the next frame length check may throw an IOException and // interrupt iterating File Writers. (see bug 4351296) // throws IllegalArgumentException if not supported AiffFileFormat aiffFileFormat = (AiffFileFormat)getAudioFileFormat(fileType, stream); // we must know the total data length to calculate the file length if( stream.getFrameLength() == AudioSystem.NOT_SPECIFIED ) { throw new IOException("stream length not specified"); } int bytesWritten = writeAiffFile(stream, aiffFileFormat, out); return bytesWritten; }
Example #25
Source File: RecordingThread.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
/** * Constructs a new object. * @param stream the stream where to write the recording. * @param recordingFormat the audio format of the recording * @throws LineUnavailableException */ RecordingThread(final OutputStream stream, final AudioFormat recordingFormat) throws LineUnavailableException { out = stream; format = recordingFormat; shouldStop = false; setDaemon(true); setName("RecordingThread"); line = AudioSystem.getTargetDataLine(format); line.open(); }
Example #26
Source File: AbstractDataLine.java From Bytecoder with Apache License 2.0 | 5 votes |
@Override public final long getMicrosecondPosition() { long microseconds = getLongFramePosition(); if (microseconds != AudioSystem.NOT_SPECIFIED) { microseconds = Toolkit.frames2micros(getFormat(), microseconds); } return microseconds; }
Example #27
Source File: PCM_FLOAT_support.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
static boolean test(Encoding enc) { out("conversion " + enc + " -> PCM_FLOAT:"); Encoding[] encodings = AudioSystem.getTargetEncodings(enc); for (Encoding e: encodings) { if (e.equals(pcmFloatEnc)) { out(" - OK"); return true; } } out(" - FAILED (not supported)"); testFailed = true; return false; }
Example #28
Source File: SoftMixingClip.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
protected void processControlLogic() { _rightgain = rightgain; _leftgain = leftgain; _eff1gain = eff1gain; _eff2gain = eff2gain; if (active_sg) { _active = active; active_sg = false; } else { active = _active; } if (frameposition_sg) { _frameposition = frameposition; frameposition_sg = false; afis = null; } else { frameposition = _frameposition; } if (loop_sg) { _loopcount = loopcount; _loopstart = loopstart; _loopend = loopend; } if (afis == null) { afis = AudioFloatInputStream.getInputStream(new AudioInputStream( datastream, format, AudioSystem.NOT_SPECIFIED)); if (Math.abs(format.getSampleRate() - outputformat.getSampleRate()) > 0.000001) afis = new AudioFloatInputStreamResampler(afis, outputformat); } }
Example #29
Source File: AudioFloatInputStream.java From hottub with GNU General Public License v2.0 | 5 votes |
public static AudioFloatInputStream getInputStream(AudioFormat format, byte[] buffer, int offset, int len) { AudioFloatConverter converter = AudioFloatConverter .getConverter(format); if (converter != null) return new BytaArrayAudioFloatInputStream(converter, buffer, offset, len); InputStream stream = new ByteArrayInputStream(buffer, offset, len); long aLen = format.getFrameSize() == AudioSystem.NOT_SPECIFIED ? AudioSystem.NOT_SPECIFIED : len / format.getFrameSize(); AudioInputStream astream = new AudioInputStream(stream, format, aLen); return getInputStream(astream); }
Example #30
Source File: SoftMixingClip.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
public void open(AudioInputStream stream) throws LineUnavailableException, IOException { if (isOpen()) { throw new IllegalStateException("Clip is already open with format " + getFormat() + " and frame lengh of " + getFrameLength()); } if (AudioFloatConverter.getConverter(stream.getFormat()) == null) throw new IllegalArgumentException("Invalid format : " + stream.getFormat().toString()); if (stream.getFrameLength() != AudioSystem.NOT_SPECIFIED) { byte[] data = new byte[(int) stream.getFrameLength() * stream.getFormat().getFrameSize()]; int readsize = 512 * stream.getFormat().getFrameSize(); int len = 0; while (len != data.length) { if (readsize > data.length - len) readsize = data.length - len; int ret = stream.read(data, len, readsize); if (ret == -1) break; if (ret == 0) Thread.yield(); len += ret; } open(stream.getFormat(), data, 0, len); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[512 * stream.getFormat().getFrameSize()]; int r = 0; while ((r = stream.read(b)) != -1) { if (r == 0) Thread.yield(); baos.write(b, 0, r); } open(stream.getFormat(), baos.toByteArray(), 0, baos.size()); } }