get Audio File Bytes - Java javax.sound.sampled

Java examples for javax.sound.sampled:Audio

Description

get Audio File Bytes

Demo Code


//package com.java2s;
import javax.sound.sampled.*;
import java.io.*;

public class Main {
    public static byte[] getAudioFileBytes(File audioFile,
            AudioFormat audioFormat) {
        AudioInputStream ais = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {/* ww w.j  av a  2s  . c  o  m*/
            ais = AudioSystem.getAudioInputStream(audioFile);
            int bufferSize = (int) audioFormat.getSampleRate()
                    * audioFormat.getFrameSize();
            byte buffer[] = new byte[bufferSize];
            int count = -1;
            while ((count = ais.read(buffer, 0, buffer.length)) > 0) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byteArrayOutputStream.flush();
            byteArrayOutputStream.close();

        } catch (IOException e) {
            System.err.println("I/O problems: " + e);

        } catch (UnsupportedAudioFileException e) {
            System.err.println(e.toString());
        } finally {
            try {
                if (ais != null) {
                    ais.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return byteArrayOutputStream.toByteArray();
    }
}

Related Tutorials