Java Sound File sliceWav(InputStream is, long starttime, long duration)

Here you can find the source of sliceWav(InputStream is, long starttime, long duration)

Description

slice Wav

License

Open Source License

Declaration

public static byte[] sliceWav(InputStream is, long starttime, long duration)
        throws UnsupportedAudioFileException, IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.AudioFileFormat.Type;

public class Main {

    public static byte[] sliceWav(InputStream is, long starttime, long duration)
            throws UnsupportedAudioFileException, IOException {
        AudioInputStream sourceStream = AudioSystem.getAudioInputStream(is);
        AudioFormat format = sourceStream.getFormat();

        int bytesPerSecond = format.getFrameSize() * (int) format.getFrameRate();
        sourceStream.skip(starttime * bytesPerSecond / 1000);
        long framesOfAudioToCopy = duration * (int) format.getFrameRate() / 1000;
        if (duration == 0) {
            framesOfAudioToCopy = sourceStream.getFrameLength() * format.getFrameSize()
                    - starttime * bytesPerSecond / 1000;
        }/*from w ww . java2  s  . co m*/
        AudioInputStream shortenedStream = new AudioInputStream(is, format, framesOfAudioToCopy);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        AudioSystem.write(shortenedStream, Type.WAVE, bos);
        // System.out.println("sliced WAV status - offset : " + (starttime *
        // bytesPerSecond / 1000) + " len : " + framesOfAudioToCopy);
        return bos.toByteArray();
    }
}

Related

  1. durationMillis(String audioPath)
  2. getAudioDuration(final URI wavFile)
  3. getAudioDuration(final URI wavFile)