javax.sound.sampled.AudioInputStream Java Examples

The following examples show how to use javax.sound.sampled.AudioInputStream. 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: WaveFloatFileWriter.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void write(AudioInputStream stream, RIFFWriter writer)
        throws IOException {

    RIFFWriter fmt_chunk = writer.writeChunk("fmt ");

    AudioFormat format = stream.getFormat();
    fmt_chunk.writeUnsignedShort(3); // WAVE_FORMAT_IEEE_FLOAT
    fmt_chunk.writeUnsignedShort(format.getChannels());
    fmt_chunk.writeUnsignedInt((int) format.getSampleRate());
    fmt_chunk.writeUnsignedInt(((int) format.getFrameRate())
            * format.getFrameSize());
    fmt_chunk.writeUnsignedShort(format.getFrameSize());
    fmt_chunk.writeUnsignedShort(format.getSampleSizeInBits());
    fmt_chunk.close();
    RIFFWriter data_chunk = writer.writeChunk("data");
    byte[] buff = new byte[1024];
    int len;
    while ((len = stream.read(buff, 0, buff.length)) != -1)
        data_chunk.write(buff, 0, len);
    data_chunk.close();
}
 
Example #2
Source File: AuFileWriter.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 #3
Source File: AuFileWriter.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public Type[] getAudioFileTypes(AudioInputStream stream) {

    Type[] filetypes = new 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)
            || AudioFormat.Encoding.PCM_FLOAT.equals(encoding)) {
        return filetypes;
    }

    return new Type[0];
}
 
Example #4
Source File: AudioFloatFormatConverter.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public AudioInputStream getAudioInputStream(Encoding targetEncoding,
                                            AudioInputStream sourceStream) {
    if (!isConversionSupported(targetEncoding, sourceStream.getFormat())) {
        throw new IllegalArgumentException(
                "Unsupported conversion: " + sourceStream.getFormat()
                        .toString() + " to " + targetEncoding.toString());
    }
    if (sourceStream.getFormat().getEncoding().equals(targetEncoding))
        return sourceStream;
    AudioFormat format = sourceStream.getFormat();
    int channels = format.getChannels();
    Encoding encoding = targetEncoding;
    float samplerate = format.getSampleRate();
    int bits = format.getSampleSizeInBits();
    boolean bigendian = format.isBigEndian();
    if (targetEncoding.equals(Encoding.PCM_FLOAT))
        bits = 32;
    AudioFormat targetFormat = new AudioFormat(encoding, samplerate, bits,
            channels, channels * bits / 8, samplerate, bigendian);
    return getAudioInputStream(targetFormat, sourceStream);
}
 
Example #5
Source File: WaveEngine.java    From javagame with MIT License 6 votes vote down vote up
/**
 * 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 #6
Source File: SoftAudioPusher.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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();
    }

}
 
Example #7
Source File: WaveEngine.java    From javagame with MIT License 6 votes vote down vote up
/**
 * 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: AudioFileSoundbankReader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 #9
Source File: AiffFileReader.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Obtains an audio stream from the File provided.  The File must
 * point to valid audio file data.
 * @param file the File for which the <code>AudioInputStream</code> should be
 * constructed
 * @return an <code>AudioInputStream</code> object based on the audio file data pointed
 * to by the File
 * @throws UnsupportedAudioFileException if the File does not point to valid audio
 * file data recognized by the system
 * @throws IOException if an I/O exception occurs
 */
public AudioInputStream getAudioInputStream(File file)
    throws UnsupportedAudioFileException, IOException {

    FileInputStream fis = new FileInputStream(file); // throws IOException
    AudioFileFormat fileFormat = null;
    // part of fix for 4325421
    try {
        fileFormat = getCOMM(fis, false);
    } finally {
        if (fileFormat == null) {
            fis.close();
        }
    }
    return new AudioInputStream(fis, fileFormat.getFormat(), fileFormat.getFrameLength());
}
 
Example #10
Source File: AlawEncoderSync.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@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 #11
Source File: SunFileReader.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public AudioInputStream getAudioInputStream(final InputStream stream)
        throws UnsupportedAudioFileException, IOException {
    stream.mark(200); // The biggest value which was historically used
    try {
        final StandardFileFormat format = getAudioFileFormatImpl(stream);
        // we've got everything, the stream is supported and it is at the
        // beginning of the audio data, so return an AudioInputStream
        return new AudioInputStream(stream, format.getFormat(),
                                    format.getLongFrameLength());
    } catch (UnsupportedAudioFileException | EOFException ignored) {
        // stream is unsupported or the header is less than was expected
        stream.reset();
        throw new UnsupportedAudioFileException();
    }
}
 
Example #12
Source File: WriteAuUnspecifiedLength.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String argv[]) throws Exception {
    AudioFormat format = new AudioFormat(44100, 16, 2, true, true);
    InputStream is = new ByteArrayInputStream(new byte[1000]);
    AudioInputStream ais = new AudioInputStream(is, format, AudioSystem.NOT_SPECIFIED);
    AudioSystem.write(ais, AudioFileFormat.Type.AU, new ByteArrayOutputStream());
    System.out.println("Test passed.");
}
 
Example #13
Source File: WaveFileReader.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Obtains an audio stream from the File provided.  The File must
 * point to valid audio file data.
 * @param file the File for which the <code>AudioInputStream</code> should be
 * constructed
 * @return an <code>AudioInputStream</code> object based on the audio file data pointed
 * to by the File
 * @throws UnsupportedAudioFileException if the File does not point to valid audio
 * file data recognized by the system
 * @throws IOException if an I/O exception occurs
 */
public AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException {
    FileInputStream fis = new FileInputStream(file); // throws IOException
    AudioFileFormat fileFormat = null;
    // part of fix for 4325421
    try {
        fileFormat = getFMT(fis, false);
    } finally {
        if (fileFormat == null) {
            fis.close();
        }
    }
    return new AudioInputStream(fis, fileFormat.getFormat(), fileFormat.getFrameLength());
}
 
Example #14
Source File: FrameLengthAfterConversion.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static AudioInputStream getStream(final AudioFormat format,
                                          final boolean frameLength) {
    final int dataSize = FRAME_LENGTH * format.getFrameSize();
    final InputStream in = new ByteArrayInputStream(new byte[dataSize]);
    if (frameLength) {
        return new AudioInputStream(in, format, FRAME_LENGTH);
    } else {
        return new AudioInputStream(in, format, NOT_SPECIFIED);
    }
}
 
Example #15
Source File: AudioFloatInputStream.java    From jdk8u-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 #16
Source File: AudioFileSoundbankReader.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public Soundbank getSoundbank(AudioInputStream ais)
        throws InvalidMidiDataException, IOException {
    try {
        byte[] buffer;
        if (ais.getFrameLength() == -1) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buff = new byte[1024
                    - (1024 % ais.getFormat().getFrameSize())];
            int ret;
            while ((ret = ais.read(buff)) != -1) {
                baos.write(buff, 0, ret);
            }
            ais.close();
            buffer = baos.toByteArray();
        } else {
            buffer = new byte[(int) (ais.getFrameLength()
                                * ais.getFormat().getFrameSize())];
            new DataInputStream(ais).readFully(buffer);
        }
        ModelByteBufferWavetable osc = new ModelByteBufferWavetable(
                new ModelByteBuffer(buffer), ais.getFormat(), -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 (Exception e) {
        return null;
    }
}
 
Example #17
Source File: JavaSoundAudioClip.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private boolean loadAudioData(AudioInputStream as)  throws IOException, UnsupportedAudioFileException {
    if (DEBUG || Printer.debug)Printer.debug("JavaSoundAudioClip->openAsClip()");

    // first possibly convert this stream to PCM
    as = Toolkit.getPCMConvertedAudioInputStream(as);
    if (as == null) {
        return false;
    }

    loadedAudioFormat = as.getFormat();
    long frameLen = as.getFrameLength();
    int frameSize = loadedAudioFormat.getFrameSize();
    long byteLen = AudioSystem.NOT_SPECIFIED;
    if (frameLen != AudioSystem.NOT_SPECIFIED
        && frameLen > 0
        && frameSize != AudioSystem.NOT_SPECIFIED
        && frameSize > 0) {
        byteLen = frameLen * frameSize;
    }
    if (byteLen != AudioSystem.NOT_SPECIFIED) {
        // if the stream length is known, it can be efficiently loaded into memory
        readStream(as, byteLen);
    } else {
        // otherwise we use a ByteArrayOutputStream to load it into memory
        readStream(as);
    }

    // if everything went fine, we have now the audio data in
    // loadedAudio, and the byte length in loadedAudioByteLength
    return true;
}
 
Example #18
Source File: WaveFloatFileWriter.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
public int write(AudioInputStream stream, Type fileType, File out)
        throws IOException {
    checkFormat(fileType, stream);
    if (stream.getFormat().isBigEndian())
        stream = toLittleEndian(stream);
    RIFFWriter writer = new RIFFWriter(out, "WAVE");
    write(stream, writer);
    int fpointer = (int) writer.getFilePointer();
    writer.close();
    return fpointer;
}
 
Example #19
Source File: DataClip.java    From javagame with MIT License 5 votes vote down vote up
public DataClip(AudioInputStream audioStream) throws IOException {
    index = 0;
    format = audioStream.getFormat();

    // WAVE�t�@�C���̑傫�������߂�
    int length = (int)(audioStream.getFrameLength() * format.getFrameSize());
    // ���̑傫����byte�z���p��
    data = new byte[length];
    // data��WAVE�f�[�^���i�[����
    DataInputStream is = new DataInputStream(audioStream);
    is.readFully(data);
}
 
Example #20
Source File: DesktopAudioRecordingService.java    From attach with GNU General Public License v3.0 5 votes vote down vote up
private void save(String fileName) throws IOException {
    byte[] audioData = recordBytes.toByteArray();
    final File wavFile = new File(getAudioFolder(), fileName + ".wav");
    ByteArrayInputStream bais = new ByteArrayInputStream(audioData);
    try (AudioInputStream audioInputStream = new AudioInputStream(bais, format, audioData.length / format.getFrameSize())) {
        AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, wavFile);
    }
    recordBytes.close();
    if (debug) {
        LOG.log(Level.INFO, String.format("File %s.wav added to %s", fileName, getAudioFolder()));
    }
    addChunk.apply(fileName + ".wav");
}
 
Example #21
Source File: AiffFileReader.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Obtains an audio stream from the URL provided.  The URL must
 * point to valid audio file data.
 * @param url the URL for which the <code>AudioInputStream</code> should be
 * constructed
 * @return an <code>AudioInputStream</code> object based on the audio file data pointed
 * to by the URL
 * @throws UnsupportedAudioFileException if the URL does not point to valid audio
 * file data recognized by the system
 * @throws IOException if an I/O exception occurs
 */
public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException {
    InputStream urlStream = url.openStream();  // throws IOException
    AudioFileFormat fileFormat = null;
    try {
        fileFormat = getCOMM(urlStream, false);
    } finally {
        if (fileFormat == null) {
            urlStream.close();
        }
    }
    return new AudioInputStream(urlStream, fileFormat.getFormat(), fileFormat.getFrameLength());
}
 
Example #22
Source File: AudioFloatInputStream.java    From jdk8u60 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 #23
Source File: AlawCodec.java    From Bytecoder with Apache License 2.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 #24
Source File: WaveFloatFileWriter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void checkFormat(AudioFileFormat.Type type, AudioInputStream stream) {
    if (!Type.WAVE.equals(type))
        throw new IllegalArgumentException("File type " + type
                + " not supported.");
    if (!stream.getFormat().getEncoding().equals(Encoding.PCM_FLOAT))
        throw new IllegalArgumentException("File format "
                + stream.getFormat() + " not supported.");
}
 
Example #25
Source File: WaveFileWriter.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeWaveFile(stream, waveFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( waveFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            int dataLength=bytesWritten-waveFileFormat.getHeaderSize();
            int riffLength=dataLength + waveFileFormat.getHeaderSize() - 8;

            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            // skip RIFF magic
            raf.skipBytes(4);
            raf.writeInt(big2little( riffLength ));
            // skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic
            raf.skipBytes(4+4+4+WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType())+4);
            raf.writeInt(big2little( dataLength ));
            // that's all
            raf.close();
        }

        return bytesWritten;
    }
 
Example #26
Source File: AudioFloatFormatConverter.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public AudioInputStream getAudioInputStream(AudioFormat targetFormat,
        AudioInputStream sourceStream) {
    if (!isConversionSupported(targetFormat, sourceStream.getFormat()))
        throw new IllegalArgumentException("Unsupported conversion: "
                + sourceStream.getFormat().toString() + " to "
                + targetFormat.toString());
    return getAudioInputStream(targetFormat, AudioFloatInputStream
            .getInputStream(sourceStream));
}
 
Example #27
Source File: DLSSample.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public Object getData() {
    AudioFormat format = getFormat();

    InputStream is = data.getInputStream();
    if (is == null)
        return null;
    return new AudioInputStream(is, format, data.capacity());
}
 
Example #28
Source File: WaveFileWriter.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeWaveFile(stream, waveFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( waveFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            int dataLength=bytesWritten-waveFileFormat.getHeaderSize();
            int riffLength=dataLength + waveFileFormat.getHeaderSize() - 8;

            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            // skip RIFF magic
            raf.skipBytes(4);
            raf.writeInt(big2little( riffLength ));
            // skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic
            raf.skipBytes(4+4+4+WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType())+4);
            raf.writeInt(big2little( dataLength ));
            // that's all
            raf.close();
        }

        return bytesWritten;
    }
 
Example #29
Source File: AuFileWriter.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeAuFile(stream, auFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            // $$kk: 10.22.99: jan: please either implement this or throw an exception!
            // $$fb: 2001-07-13: done. Fixes Bug 4479981
            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            if (raf.length()<=0x7FFFFFFFl) {
                // skip AU magic and data offset field
                raf.skipBytes(8);
                raf.writeInt(bytesWritten-AuFileFormat.AU_HEADERSIZE);
                // that's all
            }
            raf.close();
        }

        return bytesWritten;
    }
 
Example #30
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);
    }
}