-1

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());
khelwood
  • 55,782
  • 14
  • 81
  • 108
P4L
  • 1
  • Does this answer your question? [Java FileInputStream](https://stackoverflow.com/questions/15489903/java-fileinputstream) – dey Feb 28 '23 at 09:58
  • possible duplicate: https://stackoverflow.com/questions/15489903/java-fileinputstream – dey Feb 28 '23 at 09:58
  • Does this answer your question? [Read a binary file in Java](https://stackoverflow.com/questions/5470812/read-a-binary-file-in-java) – Torben Feb 28 '23 at 10:03

2 Answers2

0

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;
    }
HariHaravelan
  • 1,041
  • 1
  • 10
  • 19
0

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
        
Raushan Kumar
  • 1,195
  • 12
  • 21