javax.sound.sampled.AudioFormat Java Examples

The following examples show how to use javax.sound.sampled.AudioFormat. 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: AudioFloatFormatConverter.java    From Bytecoder with Apache License 2.0 7 votes vote down vote up
public AudioInputStream getAudioInputStream(AudioFormat targetFormat,
        AudioFloatInputStream sourceStream) {

    if (!isConversionSupported(targetFormat, sourceStream.getFormat()))
        throw new IllegalArgumentException("Unsupported conversion: "
                + sourceStream.getFormat().toString() + " to "
                + targetFormat.toString());
    if (targetFormat.getChannels() != sourceStream.getFormat()
            .getChannels())
        sourceStream = new AudioFloatInputStreamChannelMixer(sourceStream,
                targetFormat.getChannels());
    if (Math.abs(targetFormat.getSampleRate()
            - sourceStream.getFormat().getSampleRate()) > 0.000001)
        sourceStream = new AudioFloatInputStreamResampler(sourceStream,
                targetFormat);
    return new AudioInputStream(new AudioFloatFormatConverterInputStream(
            targetFormat, sourceStream), targetFormat, sourceStream
            .getFrameLength());
}
 
Example #2
Source File: TestInstantaneousFrequencySpectrum.java    From jipes with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testLinearFrequencySpectrumConstructor() {
    final float[] realValues = {1, 2, 3, 4, 5, 6};
    final float[] imagValues = {1, 1, 1, 1, 1, 1};
    final AudioFormat audioFormat = new AudioFormat(10, 16, 1, true, false);

    final LinearFrequencySpectrum linearSpectrum1 = new LinearFrequencySpectrum(2, realValues, imagValues, audioFormat);
    final LinearFrequencySpectrum linearSpectrum2 = new LinearFrequencySpectrum(3, realValues, imagValues, audioFormat);
    final InstantaneousFrequencySpectrum instantaneousSpectrum = new InstantaneousFrequencySpectrum(linearSpectrum1, linearSpectrum2);

    assertEquals(linearSpectrum1.getFrameNumber(), instantaneousSpectrum.getFrameNumber());

    assertEquals(realValues.length, instantaneousSpectrum.getNumberOfSamples());

    assertArrayEquals(toMagnitudes(realValues, imagValues, realValues.length/2), instantaneousSpectrum.getMagnitudes(), 0.000001f);
    assertArrayEquals(toPowers(realValues, imagValues, realValues.length/2), instantaneousSpectrum.getPowers(), 0.000001f);
    assertArrayEquals(toMagnitudes(realValues, imagValues, realValues.length/2), instantaneousSpectrum.getData(), 0.000001f);

    assertEquals(audioFormat, instantaneousSpectrum.getAudioFormat());
    assertEquals((long)(instantaneousSpectrum.getFrameNumber()*1000L/audioFormat.getSampleRate()), instantaneousSpectrum.getTimestamp());
    assertEquals((long) (instantaneousSpectrum.getFrameNumber() * 1000L * 1000L / audioFormat.getSampleRate()), instantaneousSpectrum.getTimestamp(TimeUnit.MICROSECONDS));

    // we have two spectra, that are exactly the same -> frequencies must be 0
    assertArrayEquals(new float[]{0.0f, 0.0f, 0.0f}, instantaneousSpectrum.getFrequencies(), 0.000001f);
}
 
Example #3
Source File: AiffFileWriter.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream stream) {

        AudioFileFormat.Type[] filetypes = new AudioFileFormat.Type[types.length];
        System.arraycopy(types, 0, filetypes, 0, types.length);

        // make sure we can write this stream
        AudioFormat format = stream.getFormat();
        AudioFormat.Encoding encoding = format.getEncoding();

        if( (AudioFormat.Encoding.ALAW.equals(encoding)) ||
            (AudioFormat.Encoding.ULAW.equals(encoding)) ||
            (AudioFormat.Encoding.PCM_SIGNED.equals(encoding)) ||
            (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding)) ) {

            return filetypes;
        }

        return new AudioFileFormat.Type[0];
    }
 
Example #4
Source File: AuFileWriter.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream stream) {

        AudioFileFormat.Type[] filetypes = new AudioFileFormat.Type[types.length];
        System.arraycopy(types, 0, filetypes, 0, types.length);

        // make sure we can write this stream
        AudioFormat format = stream.getFormat();
        AudioFormat.Encoding encoding = format.getEncoding();

        if( (AudioFormat.Encoding.ALAW.equals(encoding)) ||
            (AudioFormat.Encoding.ULAW.equals(encoding)) ||
            (AudioFormat.Encoding.PCM_SIGNED.equals(encoding)) ||
            (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding)) ) {

            return filetypes;
        }

        return new AudioFileFormat.Type[0];
    }
 
Example #5
Source File: SoundUtils.java    From Neural-Network-Programming-with-Java-SecondEdition with MIT License 6 votes vote down vote up
public static void tone(int hz, int msecs, double vol) throws LineUnavailableException {
	byte[] buf = new byte[1];
	AudioFormat af = new AudioFormat(SAMPLE_RATE, // sampleRate
			8, // sampleSizeInBits
			1, // channels
			true, // signed
			false); // bigEndian
	SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
	sdl.open(af);
	sdl.start();
	for (int i = 0; i < msecs * 8; i++) {
		double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
		buf[0] = (byte) (Math.sin(angle) * 127.0 * vol);
		sdl.write(buf, 0, 1);
	}

	sdl.drain();
	sdl.stop();
	sdl.close();
}
 
Example #6
Source File: bug6372428.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #7
Source File: TestRealAudioMatrix.java    From jipes with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testBasics() {
    final int frameNumber = 3;
    final Matrix realData = new FullMatrix(5, 6);
    final AudioFormat audioFormat = new AudioFormat(10, 8, 2, true, false);
    final RealAudioMatrix matrix = new RealAudioMatrix(frameNumber, realData, audioFormat);

    assertEquals(frameNumber, matrix.getFrameNumber());
    assertEquals(realData.getNumberOfRows(), matrix.getNumberOfSamples());
    assertArrayEquals(realData.getRow(0), matrix.getRealData(), 0.000001f);
    assertArrayEquals(new float[realData.getNumberOfColumns()], matrix.getImaginaryData(), 0.000001f);
    assertEquals(audioFormat, matrix.getAudioFormat());
    assertEquals((long) (frameNumber * 1000L / audioFormat.getSampleRate()), matrix.getTimestamp());
    assertEquals((long) (frameNumber * 1000L * 1000L / audioFormat.getSampleRate()), matrix.getTimestamp(TimeUnit.MICROSECONDS));

    assertArrayEquals(toMagnitudes(realData.getRow(0), null), matrix.getMagnitudes(), 0.000001f);
    assertArrayEquals(toPowers(realData.getRow(0), null), matrix.getPowers(), 0.000001f);
    assertArrayEquals(toMagnitudes(realData.getRow(0), null), matrix.getData(), 0.000001f);
}
 
Example #8
Source File: AiffFileWriter.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream stream) {

        AudioFileFormat.Type[] filetypes = new AudioFileFormat.Type[types.length];
        System.arraycopy(types, 0, filetypes, 0, types.length);

        // make sure we can write this stream
        AudioFormat format = stream.getFormat();
        AudioFormat.Encoding encoding = format.getEncoding();

        if( (AudioFormat.Encoding.ALAW.equals(encoding)) ||
            (AudioFormat.Encoding.ULAW.equals(encoding)) ||
            (AudioFormat.Encoding.PCM_SIGNED.equals(encoding)) ||
            (AudioFormat.Encoding.PCM_UNSIGNED.equals(encoding)) ) {

            return filetypes;
        }

        return new AudioFileFormat.Type[0];
    }
 
Example #9
Source File: CombinedAudioInputStream.java    From pumpernickel with MIT License 5 votes vote down vote up
private boolean equals(AudioFormat format1, AudioFormat format2) {
	if (format1.getChannels() != format2.getChannels())
		return false;
	if (format1.isBigEndian() != format2.isBigEndian())
		return false;
	if (format1.getSampleRate() != format2.getSampleRate())
		return false;
	if (format1.getSampleSizeInBits() != format2.getSampleSizeInBits())
		return false;
	if (!format1.getEncoding().equals(format2.getEncoding()))
		return false;

	return true;
}
 
Example #10
Source File: UlawCodec.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public AudioInputStream getAudioInputStream(AudioFormat targetFormat, AudioInputStream sourceStream){
    if (!isConversionSupported(targetFormat, sourceStream.getFormat()))
        throw new IllegalArgumentException("Unsupported conversion: "
                                           + sourceStream.getFormat().toString() + " to "
                                           + targetFormat.toString());
    return getConvertedStream(targetFormat, sourceStream);
}
 
Example #11
Source File: AudioFloatInputStream.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
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 #12
Source File: Recognize.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Performs microphone streaming speech recognition with a duration of 1 minute. */
public static void streamingMicRecognize() throws Exception {

  ResponseObserver<StreamingRecognizeResponse> responseObserver = null;
  try (SpeechClient client = SpeechClient.create()) {

    responseObserver =
        new ResponseObserver<StreamingRecognizeResponse>() {
          ArrayList<StreamingRecognizeResponse> responses = new ArrayList<>();

          public void onStart(StreamController controller) {}

          public void onResponse(StreamingRecognizeResponse response) {
            responses.add(response);
          }

          public void onComplete() {
            for (StreamingRecognizeResponse response : responses) {
              StreamingRecognitionResult result = response.getResultsList().get(0);
              SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
              System.out.printf("Transcript : %s\n", alternative.getTranscript());
            }
          }

          public void onError(Throwable t) {
            System.out.println(t);
          }
        };

    ClientStream<StreamingRecognizeRequest> clientStream =
        client.streamingRecognizeCallable().splitCall(responseObserver);

    RecognitionConfig recognitionConfig =
        RecognitionConfig.newBuilder()
            .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
            .setLanguageCode("en-US")
            .setSampleRateHertz(16000)
            .build();
    StreamingRecognitionConfig streamingRecognitionConfig =
        StreamingRecognitionConfig.newBuilder().setConfig(recognitionConfig).build();

    StreamingRecognizeRequest request =
        StreamingRecognizeRequest.newBuilder()
            .setStreamingConfig(streamingRecognitionConfig)
            .build(); // The first request in a streaming call has to be a config

    clientStream.send(request);
    // SampleRate:16000Hz, SampleSizeInBits: 16, Number of channels: 1, Signed: true,
    // bigEndian: false
    AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false);
    DataLine.Info targetInfo =
        new Info(
            TargetDataLine.class,
            audioFormat); // Set the system information to read from the microphone audio stream

    if (!AudioSystem.isLineSupported(targetInfo)) {
      System.out.println("Microphone not supported");
      System.exit(0);
    }
    // Target data line captures the audio stream the microphone produces.
    TargetDataLine targetDataLine = (TargetDataLine) AudioSystem.getLine(targetInfo);
    targetDataLine.open(audioFormat);
    targetDataLine.start();
    System.out.println("Start speaking");
    long startTime = System.currentTimeMillis();
    // Audio Input Stream
    AudioInputStream audio = new AudioInputStream(targetDataLine);
    while (true) {
      long estimatedTime = System.currentTimeMillis() - startTime;
      byte[] data = new byte[6400];
      audio.read(data);
      if (estimatedTime > 60000) { // 60 seconds
        System.out.println("Stop speaking.");
        targetDataLine.stop();
        targetDataLine.close();
        break;
      }
      request =
          StreamingRecognizeRequest.newBuilder()
              .setAudioContent(ByteString.copyFrom(data))
              .build();
      clientStream.send(request);
    }
  } catch (Exception e) {
    System.out.println(e);
  }
  responseObserver.onComplete();
}
 
Example #13
Source File: TestDecimate.java    From jipes with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testProcess() throws IOException {
    final Decimate decimate = new Decimate(500f);
    final AudioBuffer buffer = decimate.processNext(new RealAudioBuffer(0, new float[100], new AudioFormat(1000f, 8, 1, true, true)));
    assertArrayEquals(new float[50], buffer.getData(), 0.0001f);
    decimate.processNext(new RealAudioBuffer(1, new float[100], new AudioFormat(1000f, 8, 1, true, true)));
}
 
Example #14
Source File: TestPreciseTimestampRendering.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static Soundbank createTestSoundbankWithChannelMixer() {
    SF2Soundbank soundbank = createTestSoundbank();

    SimpleSoundbank simplesoundbank = new SimpleSoundbank();
    SimpleInstrument simpleinstrument = new SimpleInstrument() {

        public ModelChannelMixer getChannelMixer(MidiChannel channel,
                AudioFormat format) {
            return new ModelAbstractChannelMixer() {
                boolean active = true;

                public boolean process(float[][] buffer, int offset, int len) {
                    for (int i = 0; i < buffer.length; i++) {
                        float[] cbuffer = buffer[i];
                        for (int j = 0; j < cbuffer.length; j++) {
                            cbuffer[j] = -cbuffer[j];
                        }
                    }
                    return active;
                }

                public void stop() {
                    active = false;
                }
            };
        }

    };
    simpleinstrument.add(soundbank.getInstruments()[0]);
    simplesoundbank.addInstrument(simpleinstrument);

    return simplesoundbank;
}
 
Example #15
Source File: AudioPlayer.java    From pumpernickel with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: FormatConversionProvider.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Indicates whether the format converter supports conversion from the
 * specified source format encoding.
 * @param sourceEncoding the source format encoding for which support is queried
 * @return <code>true</code> if the encoding is supported, otherwise <code>false</code>
 */
public boolean isSourceEncodingSupported(AudioFormat.Encoding sourceEncoding){

    AudioFormat.Encoding sourceEncodings[] = getSourceEncodings();

    for(int i=0; i<sourceEncodings.length; i++) {
        if( sourceEncoding.equals( sourceEncodings[i]) ) {
            return true;
        }
    }
    return false;
}
 
Example #17
Source File: MidiToAudioSynth.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
private AudioInputStream invokeOpenStream(Synthesizer synthesizer, AudioFormat audioFormat, Map<String, Object> map) throws Throwable {
	Class<?>[] methodSignature = new Class[]{AudioFormat.class,Map.class};
	Object[] methodArguments = new Object[]{audioFormat, map};
	
	Class<?> classInstance = synthesizer.getClass();
	Method method = classInstance.getMethod(SYNTHESIZER_OPEN_STREAM_METHOD, methodSignature);
	Object returnValue = method.invoke(synthesizer, methodArguments);
	
	return (AudioInputStream)returnValue;
}
 
Example #18
Source File: DirectAudioDevice.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public boolean isFormatSupportedInHardware(AudioFormat format) {
    if (format == null) return false;
    for (int i = 0; i < hardwareFormats.length; i++) {
        if (format.matches(hardwareFormats[i])) {
            return true;
        }
    }
    return false;
}
 
Example #19
Source File: AudioFloatFormatConverter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean isConversionSupported(Encoding targetEncoding,
                                     AudioFormat sourceFormat) {
    Objects.requireNonNull(targetEncoding);
    if (AudioFloatConverter.getConverter(sourceFormat) == null)
        return false;
    for (int i = 0; i < formats.length; i++) {
        if (targetEncoding.equals(formats[i]))
            return true;
    }
    return false;
}
 
Example #20
Source File: TestMultiBandSpectrum.java    From jipes with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testClone() throws CloneNotSupportedException {
    final int frameNumber = 3;
    final float[] realData = {1, 2, 3, 4, 5, 6};
    final float[] imaginaryData = {2, 3, 4, 5, 6, 7};
    final float[] boundaries = {2, 3, 4, 5, 9, 10, 11};
    final AudioFormat audioFormat = new AudioFormat(10, 16, 2, true, false);
    final MultiBandSpectrum spectrum = new MultiBandSpectrum(frameNumber, realData, imaginaryData, audioFormat, boundaries);

    final MultiBandSpectrum clone = (MultiBandSpectrum)spectrum.clone();

    assertEquals(frameNumber, clone.getFrameNumber());
    assertEquals(realData.length, clone.getNumberOfSamples());
    assertArrayEquals(realData, clone.getRealData(), 0.000001f);
    assertArrayEquals(imaginaryData, clone.getImaginaryData(), 0.000001f);
    assertEquals(audioFormat, clone.getAudioFormat());
    assertEquals(boundaries.length-1, clone.getNumberOfBands());
    assertArrayEquals(boundaries, clone.getBandBoundaries(), 0.0001f);
    assertEquals((long)(frameNumber*1000L/audioFormat.getSampleRate()), clone.getTimestamp());
    assertEquals((long) (frameNumber * 1000L * 1000L / audioFormat.getSampleRate()), clone.getTimestamp(TimeUnit.MICROSECONDS));

    assertArrayEquals(toMagnitudes(realData, imaginaryData), clone.getMagnitudes(), 0.000001f);
    assertArrayEquals(toPowers(realData, imaginaryData), clone.getPowers(), 0.000001f);
    assertArrayEquals(toMagnitudes(realData, imaginaryData), clone.getData(), 0.000001f);

    assertEquals(4.5f, clone.getFrequency(2), 0.000001f);
}
 
Example #21
Source File: EmergencySoundbank.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static SF2Sample newSimpleFFTSample_dist(SF2Soundbank sf2,
        String name, double[] data, double base, double preamp) {

    int fftsize = data.length / 2;
    AudioFormat format = new AudioFormat(44100, 16, 1, true, false);
    double basefreq = (base / fftsize) * format.getSampleRate() * 0.5;

    randomPhase(data);
    ifft(data);
    data = realPart(data);

    for (int i = 0; i < data.length; i++) {
        data[i] = (1 - Math.exp(-Math.abs(data[i] * preamp)))
                * Math.signum(data[i]);
    }

    normalize(data, 0.9);
    float[] fdata = toFloat(data);
    fdata = loopExtend(fdata, fdata.length + 512);
    fadeUp(fdata, 80);
    byte[] bdata = toBytes(fdata, format);

    /*
     * Create SoundFont2 sample.
     */
    SF2Sample sample = new SF2Sample(sf2);
    sample.setName(name);
    sample.setData(bdata);
    sample.setStartLoop(256);
    sample.setEndLoop(fftsize + 256);
    sample.setSampleRate((long) format.getSampleRate());
    double orgnote = (69 + 12)
            + (12 * Math.log(basefreq / 440.0) / Math.log(2));
    sample.setOriginalPitch((int) orgnote);
    sample.setPitchCorrection((byte) (-(orgnote - (int) orgnote) * 100.0));
    sf2.addResource(sample);

    return sample;
}
 
Example #22
Source File: StdAudio.java    From algs4 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Saves the double array as an audio file (using .wav or .au format).
 *
 * @param  filename the name of the audio file
 * @param  samples the array of samples
 * @throws IllegalArgumentException if unable to save {@code filename}
 * @throws IllegalArgumentException if {@code samples} is {@code null}
 * @throws IllegalArgumentException if {@code filename} is {@code null}
 * @throws IllegalArgumentException if {@code filename} extension is not {@code .wav}
 *         or {@code .au}
 */
public static void save(String filename, double[] samples) {
    if (filename == null) {
        throw new IllegalArgumentException("filenameis null");
    }
    if (samples == null) {
        throw new IllegalArgumentException("samples[] is null");
    }

    // assumes 16-bit samples with sample rate = 44,100 Hz
    // use 16-bit audio, mono, signed PCM, little Endian
    AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, MONO, SIGNED, LITTLE_ENDIAN);
    byte[] data = new byte[2 * samples.length];
    for (int i = 0; i < samples.length; i++) {
        int temp = (short) (samples[i] * MAX_16_BIT);
        if (samples[i] == 1.0) temp = Short.MAX_VALUE;   // special case since 32768 not a short
        data[2*i + 0] = (byte) temp;
        data[2*i + 1] = (byte) (temp >> 8);   // little endian
    }

    // now save the file
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        AudioInputStream ais = new AudioInputStream(bais, format, samples.length);
        if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
            AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename));
        }
        else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
            AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename));
        }
        else {
            throw new IllegalArgumentException("file type for saving must be .wav or .au");
        }
    }
    catch (IOException ioe) {
        throw new IllegalArgumentException("unable to save file '" + filename + "'", ioe);
    }
}
 
Example #23
Source File: SoftMixingSourceDataLine.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void open(AudioFormat format) throws LineUnavailableException {
    if (bufferSize == -1)
        bufferSize = ((int) (format.getFrameRate() / 2))
                * format.getFrameSize();
    open(format, bufferSize);
}
 
Example #24
Source File: MessageSender.java    From SpeechToText-WebSockets-Java with MIT License 5 votes vote down vote up
private static AudioInputStream toMono(AudioInputStream sourceAudioStream) {
    AudioFormat sourceFormat = sourceAudioStream.getFormat();
    return getAudioInputStream(new AudioFormat(
        sourceFormat.getEncoding(),
        sourceFormat.getSampleRate(),
        sourceFormat.getSampleSizeInBits(),
        NUM_CHANNELS,
        sourceFormat.getFrameSize(),
        sourceFormat.getFrameRate(),
        sourceFormat.isBigEndian()), sourceAudioStream);
}
 
Example #25
Source File: DesktopAudioRecordingService.java    From attach with GNU General Public License v3.0 5 votes vote down vote up
public TimedAudioCapture(TargetDataLine line, AudioFormat format, int chunk) {
    this.format = format;
    thread = new Thread(() -> {
        try {
            isRunning = line != null;
            final String fileName = String.format("audioFile-%03d-%s", chunk, LocalDateTime.now().format(pattern));
            if (debug) {
                LOG.log(Level.INFO, String.format("Start recording chunk %d", chunk));
            }

            byte[] buffer = new byte[BUFFER_SIZE];
            recordBytes = new ByteArrayOutputStream();
            while (isRunning && line != null) {
                int bytesRead = line.read(buffer, 0, buffer.length);
                recordBytes.write(buffer, 0, bytesRead);
            }

            if (debug) {
                LOG.log(Level.INFO, String.format("Save recorded chunk %d", chunk));
            }
            save(fileName);
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "Error in timedAudioCapture ", ex);
        }
    });
    thread.setName("TimedAudioCapture");
}
 
Example #26
Source File: BackgroundMusicUtils.java    From WorldGrower with GNU General Public License v3.0 5 votes vote down vote up
public static Clip readMusicFile(InputStream audioFilePath, SoundOutput soundOutput) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
	AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFilePath);
	AudioFormat format = audioStream.getFormat();
	DataLine.Info info = new DataLine.Info(Clip.class, format);
	
	Mixer mixer = soundOutput.getMixer();
	Clip audioClip = (Clip) mixer.getLine(info);
	audioClip.open(audioStream);
	return audioClip;
}
 
Example #27
Source File: SoftMixingDataLine.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public AudioFloatInputStreamResampler(AudioFloatInputStream ais,
        AudioFormat format) {
    this.ais = ais;
    AudioFormat sourceFormat = ais.getFormat();
    targetFormat = new AudioFormat(sourceFormat.getEncoding(), format
            .getSampleRate(), sourceFormat.getSampleSizeInBits(),
            sourceFormat.getChannels(), sourceFormat.getFrameSize(),
            format.getSampleRate(), sourceFormat.isBigEndian());
    nrofchannels = targetFormat.getChannels();
    Object interpolation = format.getProperty("interpolation");
    if (interpolation != null && (interpolation instanceof String)) {
        String resamplerType = (String) interpolation;
        if (resamplerType.equalsIgnoreCase("point"))
            this.resampler = new SoftPointResampler();
        if (resamplerType.equalsIgnoreCase("linear"))
            this.resampler = new SoftLinearResampler2();
        if (resamplerType.equalsIgnoreCase("linear1"))
            this.resampler = new SoftLinearResampler();
        if (resamplerType.equalsIgnoreCase("linear2"))
            this.resampler = new SoftLinearResampler2();
        if (resamplerType.equalsIgnoreCase("cubic"))
            this.resampler = new SoftCubicResampler();
        if (resamplerType.equalsIgnoreCase("lanczos"))
            this.resampler = new SoftLanczosResampler();
        if (resamplerType.equalsIgnoreCase("sinc"))
            this.resampler = new SoftSincResampler();
    }
    if (resampler == null)
        resampler = new SoftLinearResampler2(); // new
    // SoftLinearResampler2();
    pitch[0] = sourceFormat.getSampleRate() / format.getSampleRate();
    pad = resampler.getPadding();
    pad2 = pad * 2;
    ibuffer = new float[nrofchannels][buffer_len + pad2];
    ibuffer2 = new float[nrofchannels * buffer_len];
    ibuffer_index = buffer_len + pad;
    ibuffer_len = buffer_len;
}
 
Example #28
Source File: AudioFloatFormatConverter.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
AudioFloatInputStreamResampler(AudioFloatInputStream ais,
        AudioFormat format) {
    this.ais = ais;
    AudioFormat sourceFormat = ais.getFormat();
    targetFormat = new AudioFormat(sourceFormat.getEncoding(), format
            .getSampleRate(), sourceFormat.getSampleSizeInBits(),
            sourceFormat.getChannels(), sourceFormat.getFrameSize(),
            format.getSampleRate(), sourceFormat.isBigEndian());
    nrofchannels = targetFormat.getChannels();
    Object interpolation = format.getProperty("interpolation");
    if (interpolation != null && (interpolation instanceof String)) {
        String resamplerType = (String) interpolation;
        if (resamplerType.equalsIgnoreCase("point"))
            this.resampler = new SoftPointResampler();
        if (resamplerType.equalsIgnoreCase("linear"))
            this.resampler = new SoftLinearResampler2();
        if (resamplerType.equalsIgnoreCase("linear1"))
            this.resampler = new SoftLinearResampler();
        if (resamplerType.equalsIgnoreCase("linear2"))
            this.resampler = new SoftLinearResampler2();
        if (resamplerType.equalsIgnoreCase("cubic"))
            this.resampler = new SoftCubicResampler();
        if (resamplerType.equalsIgnoreCase("lanczos"))
            this.resampler = new SoftLanczosResampler();
        if (resamplerType.equalsIgnoreCase("sinc"))
            this.resampler = new SoftSincResampler();
    }
    if (resampler == null)
        resampler = new SoftLinearResampler2(); // new
                                                // SoftLinearResampler2();
    pitch[0] = sourceFormat.getSampleRate() / format.getSampleRate();
    pad = resampler.getPadding();
    pad2 = pad * 2;
    ibuffer = new float[nrofchannels][buffer_len + pad2];
    ibuffer2 = new float[nrofchannels * buffer_len];
    ibuffer_index = buffer_len + pad;
    ibuffer_len = buffer_len;
}
 
Example #29
Source File: NoteOverFlowTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
    AudioSynthesizer synth = new SoftSynthesizer();
    AudioFormat format = new AudioFormat(44100, 16, 2, true, false);
    AudioInputStream stream = synth.openStream(format, null);

    // Make all voices busy, e.g.
    // send midi on and midi off on all available voices
    MidiChannel ch1 = synth.getChannels()[0];
    ch1.programChange(48); // Use contionus instrument like string ensemble
    for (int i = 0; i < synth.getMaxPolyphony(); i++) {
        ch1.noteOn(64, 64);
        ch1.noteOff(64);
    }

    // Now send single midi on, and midi off message
    ch1.noteOn(64, 64);
    ch1.noteOff(64);

    // Read 10 sec from stream, by this time all voices should be inactvie
    stream.skip(format.getFrameSize() * ((int)(format.getFrameRate() * 20)));

    // If no voice are active, then this test will pass
    VoiceStatus[] v = synth.getVoiceStatus();
    for (int i = 0; i < v.length; i++) {
        if(v[i].active)
        {
            throw new RuntimeException("Not all voices are inactive!");
        }
    }

    // Close the synthesizer after use
    synth.close();
}
 
Example #30
Source File: AudioPlayer.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
public AudioPlayer(InputStream in, Listener listener) throws Exception {
    this.in = in;
    this.listener = listener;

    AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, true);
    line = AudioSystem.getSourceDataLine(format);
    line.open(format);
    LOG.debug("Opened line " + line);

    if (line.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
        gainControl = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
        setGain(DEFAULT_GAIN);
    }
    new AudioDataWriter();
}