private static void init() { try { // 44,100 samples per second, 16-bit audio, mono, signed PCM, little // Endian AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false); 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(); }
public static void playGradient(double fstart,double fend,double duration,double volume,byte fadeend,byte wave) { byte[] freqdata = new byte[(int)(duration * SAMPLE_RATE)]; // Generate the sound for(int i = 0; i < freqdata.length; i++) { freqdata[i] = (byte)generateValue(i, duration, fstart + (fend-fstart) * (i/(double)freqdata.length), volume, fadeend, wave); } // Play it try { final AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, true); SourceDataLine line = AudioSystem.getSourceDataLine(af); line.open(af, SAMPLE_RATE); line.start(); line.write(freqdata, 0, freqdata.length); line.drain(); line.close(); }catch(LineUnavailableException e) { e.printStackTrace(); } }
JSAudioRecording(JSMinim sys, byte[] samps, SourceDataLine sdl, AudioMetaData mdata) { system = sys; samples = samps; meta = mdata; format = sdl.getFormat(); finished = false; line = sdl; loop = false; play = false; numLoops = 0; loopBegin = 0; loopEnd = (int)AudioUtils.millis2BytesFrameAligned( meta.length(), format ); rawBytes = new byte[sdl.getBufferSize() / 8]; iothread = null; totalBytesRead = 0; bytesWritten = 0; shouldRead = true; }
/** * Finishes the recording process by closing the file. */ public AudioRecordingStream save() { try { aos.close(); } catch (IOException e) { Minim.error("AudioRecorder.save: An error occurred when trying to save the file:\n" + e.getMessage()); } String filePath = filePath(); AudioInputStream ais = system.getAudioInputStream(filePath); SourceDataLine sdl = system.getSourceDataLine(ais.getFormat(), 1024); // this is fine because the recording will always be // in a raw format (WAV, AU, etc). long length = AudioUtils.frames2Millis(ais.getFrameLength(), format); BasicMetaData meta = new BasicMetaData(filePath, length, ais.getFrameLength()); JSPCMAudioRecordingStream recording = new JSPCMAudioRecordingStream(system, meta, ais, sdl, 1024); return recording; }
/** * Play a sound at a given frequency freq during duration (in seconds) with volume as strenght * <br/><br/> * <code>SoundGenerator.playSound(440.0,1.0,0.5,SoundGenerator.FADE_LINEAR,SoundGenerator.WAVE_SIN);</code><br/> * Available fades : FADE_NONE, FADE_LINEAR, FADE_QUADRATIC<br/> * Available waves : WAVE_SIN, WAVE_SQUARE, WAVE_TRIANGLE, WAVE_SAWTOOTH<br/> */ public static void playSound(double freq,double duration,double volume,byte fade,byte wave){ double[] soundData = generateSoundData(freq,duration,volume,fade,wave); byte[] freqdata = new byte[soundData.length]; for(int i = 0;i < soundData.length;i++) { freqdata[i] = (byte)soundData[i]; } // Play it try { final AudioFormat af = new AudioFormat(SAMPLE_RATE, 8, 1, true, true); SourceDataLine line = AudioSystem.getSourceDataLine(af); line.open(af, SAMPLE_RATE); line.start(); line.write(freqdata, 0, freqdata.length); line.drain(); line.close(); }catch(LineUnavailableException e) { e.printStackTrace(); } }
/** * Play a sound. * * @param in The {@code AudioInputStream} to play. * @return True if the stream was played without incident. * @exception IOException if unable to read or write the sound data. */ private boolean playSound(AudioInputStream in) throws IOException { boolean ret = false; SourceDataLine line = openLine(in.getFormat()); if (line == null) return false; try { startPlaying(); int rd; while (keepPlaying() && (rd = in.read(data)) > 0) { line.write(data, 0, rd); } ret = true; } finally { stopPlaying(); line.drain(); line.stop(); line.close(); } return ret; }
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; }
public void run() { byte[] buffer = SoftAudioPusher.this.buffer; AudioInputStream ais = SoftAudioPusher.this.ais; SourceDataLine sourceDataLine = SoftAudioPusher.this.sourceDataLine; try { while (active) { // Read from audio source int count = ais.read(buffer); if(count < 0) break; // Write byte buffer to source output sourceDataLine.write(buffer, 0, count); } } catch (IOException e) { active = false; //e.printStackTrace(); } }
/** Obtain the value of a default provider property. @param typeClass The type of the default provider property. This should be one of Receiver.class, Transmitter.class, Sequencer.class, Synthesizer.class, SourceDataLine.class, TargetDataLine.class, Clip.class or Port.class. @return The complete value of the property, if available. If the property is not set, null is returned. */ private static synchronized String getDefaultProvider(Class typeClass) { if (!SourceDataLine.class.equals(typeClass) && !TargetDataLine.class.equals(typeClass) && !Clip.class.equals(typeClass) && !Port.class.equals(typeClass) && !Receiver.class.equals(typeClass) && !Transmitter.class.equals(typeClass) && !Synthesizer.class.equals(typeClass) && !Sequencer.class.equals(typeClass)) { return null; } String name = typeClass.getName(); String value = AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty(name)); if (value == null) { value = getProperties().getProperty(name); } if ("".equals(value)) { value = null; } return value; }
@Override public void run() { byte[] buffer = SoftAudioPusher.this.buffer; AudioInputStream ais = SoftAudioPusher.this.ais; SourceDataLine sourceDataLine = SoftAudioPusher.this.sourceDataLine; try { while (active) { // Read from audio source int count = ais.read(buffer); if(count < 0) break; // Write byte buffer to source output sourceDataLine.write(buffer, 0, count); } } catch (IOException e) { active = false; //e.printStackTrace(); } }
/** Obtain the value of a default provider property. @param typeClass The type of the default provider property. This should be one of Receiver.class, Transmitter.class, Sequencer.class, Synthesizer.class, SourceDataLine.class, TargetDataLine.class, Clip.class or Port.class. @return The complete value of the property, if available. If the property is not set, null is returned. */ private static synchronized String getDefaultProvider(Class<?> typeClass) { if (!SourceDataLine.class.equals(typeClass) && !TargetDataLine.class.equals(typeClass) && !Clip.class.equals(typeClass) && !Port.class.equals(typeClass) && !Receiver.class.equals(typeClass) && !Transmitter.class.equals(typeClass) && !Synthesizer.class.equals(typeClass) && !Sequencer.class.equals(typeClass)) { return null; } String name = typeClass.getName(); String value = AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty(name)); if (value == null) { value = getProperties().getProperty(name); } if ("".equals(value)) { value = null; } return value; }
private static void doMixerSDL(Mixer mixer, AudioFormat format) { if (mixer==null) return; try { System.out.println("SDL from mixer "+mixer+":"); DataLine.Info info = new DataLine.Info( SourceDataLine.class, format); if (mixer.isLineSupported(info)) { SourceDataLine sdl = (SourceDataLine) mixer.getLine(info); doLine1(sdl, format); doLine2(sdl, format); } else { System.out.println(" - Line not supported"); } } catch (Throwable t) { System.out.println(" - Caught exception. Not failed."); System.out.println(" - "+t.toString()); } }
void playRecorded(AudioFormat format, byte[] data) throws Exception { //SourceDataLine line = AudioSystem.getSourceDataLine(format); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); SourceDataLine line = (SourceDataLine)AudioSystem.getLine(info); line.open(); line.start(); int remaining = data.length; while (remaining > 0) { int avail = line.available(); if (avail > 0) { if (avail > remaining) avail = remaining; int written = line.write(data, data.length - remaining, avail); remaining -= written; log("Playing: " + written + " bytes written"); } else { delay(100); } } line.drain(); line.stop(); }
@Override public void startPlayback(final ISyncAudioSource resampler) { final AudioFormat format = StreamSourceAudio.getFormat(); new Thread("Audio output") { private byte[] buffer; public void run() { try { DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); try(SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info)) { line.open(format, StreamSourceAudio.requestBufferSize); line.start(); buffer=new byte[line.getBufferSize()]; while(!resampler.isClosed()) { resampler.readOutput(buffer); line.write(buffer, 0, buffer.length); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }.start(); }
public static void main(String[] args) throws Exception { AbstractRcomArgs a=new AbstractRcomArgs(); UtilCli.parse(a, args, true); File folder=new File("/home/rizsi/tmp/video"); byte[] data=UtilFile.loadFile(new File(folder, "remote.sw")); AudioFormat format=ManualTestEchoCancel.getFormat(); final Mixer mixer = AudioSystem.getMixer(null); DataLine.Info info2= new DataLine.Info(SourceDataLine.class, format); SourceDataLine s=(SourceDataLine) mixer.getLine(info2); s.open(format, framesamples*2); s.start(); try(LoopInputStream lis=new LoopInputStream(data)) { try(JitterResampler rs=new JitterResampler(a, 8000, framesamples, 2)) { new FeedThread(lis, rs).start(); final byte[] buffer=new byte[framesamples*2];; while(true) { rs.readOutput(buffer); s.write(buffer, 0, buffer.length); } } } }
/** * Returns all available mixers. * * @return A List of available Mixers */ public List<String> getMixers() { List<String> mixers = new ArrayList<>(); // Obtains an array of mixer info objects that represents the set of // audio mixers that are currently installed on the system. Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo(); if (mixerInfos != null) Arrays.stream(mixerInfos).forEach(mInfo -> { // line info Line.Info lineInfo = new Line.Info(SourceDataLine.class); Mixer mixer = AudioSystem.getMixer(mInfo); // if line supported if (mixer.isLineSupported(lineInfo)) mixers.add(mInfo.getName()); }); return mixers; }
/** Plays audio from the given audio input stream. * * @param stream the AudioInputStream to play. * @param startTime the time to skip to when playing starts. * A value of zero means this plays from the beginning, 1 means it skips one second, etc. * @param listener an optional Listener to update. * @param cancellable an optional Cancellable to consult. * @param blocking whether this call is blocking or not. * @throws LineUnavailableException if a line is unavailable. * @throws UnsupportedOperationException if this static method doesn't support playing the stream argument **/ public static SourceDataLine playAudioStream(AudioInputStream stream,StartTime startTime,Listener listener,Cancellable cancellable,boolean blocking) throws UnsupportedOperationException, LineUnavailableException { AudioFormat audioFormat = stream.getFormat(); DataLine.Info info = new DataLine.Info( SourceDataLine.class, audioFormat ); if ( !AudioSystem.isLineSupported( info ) ) { throw new UnsupportedOperationException("AudioPlayback.playAudioStream: info="+info ); } final SourceDataLine dataLine = (SourceDataLine) AudioSystem.getLine( info ); dataLine.open( audioFormat ); dataLine.start(); PlayAudioThread thread = new PlayAudioThread(stream, startTime, dataLine, listener, cancellable); if(blocking) { thread.run(); } else { thread.start(); } return dataLine; }
@Override public boolean isVisible(JList list, Object value, int row, boolean isSelected, boolean cellHasFocus) { SoundSource sound = (SoundSource)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; }
private static void init() { try { // 44,100 samples per second, 16-bit audio, mono, signed PCM, little Endian AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false); 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(); }
public static void main(String[] args) throws LineUnavailableException, IOException { AudioPlayerManager manager = new DefaultAudioPlayerManager(); AudioSourceManagers.registerRemoteSources(manager); manager.getConfiguration().setOutputFormat(new AudioDataFormat(2, 44100, 960, AudioDataFormat.Codec.PCM_S16_BE)); AudioPlayer player = manager.createPlayer(); manager.loadItem("ytsearch: epic soundtracks", new FunctionalResultHandler(null, playlist -> { player.playTrack(playlist.getTracks().get(0)); }, null, null)); AudioDataFormat format = manager.getConfiguration().getOutputFormat(); AudioInputStream stream = AudioPlayerInputStream.createStream(player, format, 10000L, false); SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class, stream.getFormat()); SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(stream.getFormat()); line.start(); byte[] buffer = new byte[format.bufferSize(2)]; int chunkSize; while ((chunkSize = stream.read(buffer)) >= 0) { line.write(buffer, 0, chunkSize); } }
public TGMixer() { super(new Line.Info(Mixer.class)); this.lines = new HashMap<Class<?>, Line>(); this.sourceLineInfo = new ArrayList<DataLine.Info>(); this.targetLineInfo = new ArrayList<DataLine.Info>(); List<AudioFormat> formats = new ArrayList<AudioFormat>(); for (int channels = 1; channels <= 2; channels++) { formats.add(new AudioFormat(Encoding.PCM_SIGNED, AudioSystem.NOT_SPECIFIED, 8, channels, channels, AudioSystem.NOT_SPECIFIED, false)); formats.add(new AudioFormat(Encoding.PCM_UNSIGNED, AudioSystem.NOT_SPECIFIED, 8, channels, channels, AudioSystem.NOT_SPECIFIED, false)); for (int bits = 16; bits < 32; bits += 8) { formats.add(new AudioFormat(Encoding.PCM_SIGNED, AudioSystem.NOT_SPECIFIED, bits, channels, channels * bits / 8, AudioSystem.NOT_SPECIFIED, false)); formats.add(new AudioFormat(Encoding.PCM_UNSIGNED, AudioSystem.NOT_SPECIFIED, bits, channels, channels * bits / 8, AudioSystem.NOT_SPECIFIED, false)); formats.add(new AudioFormat(Encoding.PCM_SIGNED, AudioSystem.NOT_SPECIFIED, bits, channels, channels * bits / 8, AudioSystem.NOT_SPECIFIED, true)); formats.add(new AudioFormat(Encoding.PCM_UNSIGNED, AudioSystem.NOT_SPECIFIED, bits, channels, channels * bits / 8, AudioSystem.NOT_SPECIFIED, true)); } formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4, AudioSystem.NOT_SPECIFIED, false)); formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4, AudioSystem.NOT_SPECIFIED, true)); formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8, AudioSystem.NOT_SPECIFIED, false)); formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8, AudioSystem.NOT_SPECIFIED, true)); } this.sourceLineInfo.add(new DataLine.Info(SourceDataLine.class, formats.toArray(new AudioFormat[formats.size()]), AudioSystem.NOT_SPECIFIED, AudioSystem.NOT_SPECIFIED)); }
/** Checks if a Mixer is appropriate. A Mixer is considered appropriate if it support the given line type. If isMixingRequired is true and the line type is an output one (SourceDataLine, Clip), the mixer is appropriate if it supports at least 2 (concurrent) lines of the given type. @return true if the mixer is considered appropriate according to the rules given above, false otherwise. */ private static boolean isAppropriateMixer(Mixer mixer, Line.Info lineInfo, boolean isMixingRequired) { if (! mixer.isLineSupported(lineInfo)) { return false; } Class lineClass = lineInfo.getLineClass(); if (isMixingRequired && (SourceDataLine.class.isAssignableFrom(lineClass) || Clip.class.isAssignableFrom(lineClass))) { int maxLines = mixer.getMaxLines(lineInfo); return ((maxLines == NOT_SPECIFIED) || (maxLines > 1)); } return true; }
/** * Starts the player */ public void start() { try { // start source line DataLine.Info info = new DataLine.Info( SourceDataLine.class, VideoFormat.getAudioFormat()); mSourceLine = (SourceDataLine) AudioSystem.getLine(info); mSourceLine.open(VideoFormat.getAudioFormat()); mPlayerThread = new Thread(this); mPlayerThread.setDaemon(true); mPlayerThread.start(); } catch (LineUnavailableException ex) { Logs.error(getClass(), "Failed to start the audio line. ERROR: {0}", ex); } }
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(); } }
private static void reproduce( byte soundbytes[]) { try { DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, AudioFormatHelper.getAudioFormat()); // El source data line se usa para escribir datos en el SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo); sourceDataLine.open(AudioFormatHelper.getAudioFormat()); sourceDataLine.start(); sourceDataLine.write(soundbytes, 0, soundbytes.length); sourceDataLine.drain(); sourceDataLine.close(); } catch (Exception e) { // Log and Handle exception e.printStackTrace(); } }