Byte extraction in java

67 Views Asked by At

I want to extract the bytes from a wav file in Java and I don't know how. I tried this but it doesn't work:

public class AudioFiles {
    public static void main(String[] args) throws FileNotFoundException {
        File file= new File("audio.wav");
        Scanner s= new Scanner(file);
        System.out.println(s.nextLine());
2

There are 2 best solutions below

0
On

To read a .wav file as bytes in Java, you can use the java.io package to create an input stream from the .wav file and then read the bytes from the input stream.

    public static void main(String[] args) throws IOException {
       byte[] bytes = fileToBytes("/yourPath/audio.wav");
    }

    private static byte[] fileToBytes(String filePath) throws IOException {
        File file = new File(filePath);
        byte[] bytes = new byte[(int) file.length()];
        try(InputStream inputStream = Files.newInputStream(file.toPath())) {
            inputStream.read(bytes);
        }
        return bytes;
    }
0
On

Please use javax.sound.sampled.AudioInputStream to read in bytes

This is an InputStream which is specialized for reading audio files. In particular, it only allows operations to act on a multiple of the audio stream's frame size.

            File file = new File("audio.wav");
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
            byte[] audioData = new byte[(int) file.length()];
            audioInputStream.read(audioData);

OR FileInputStream:

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

        File file = new File("audio.wav");
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = inputStream.readAllBytes();//Read