Search code examples
javaaudiowavsample

Java getAudioInputStream trying to read audio file, getting javax.sound.sampled.UnsupportedAudioFileException,


I am trying to load a wav file in my java program, using the code I found here:
How do I get a sound file's total time in Java?

However, at line 14:

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);

I get the error

"Unhandled exceptions: javax.sound.sampled.UnsupportedAudioFileException, java.io.IOException"

This is my code:

import java.nio.file.FileSystems;
import java.io.File;
import java.nio.file.Path;
import javax.sound.sampled.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;

public class Main {

    public static void main(String[] args) {
        Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
        File file = new File(path+"/sample/loop1.wav");
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
        AudioFormat format = audioInputStream.getFormat();
        long audioFileLength = file.length();
        int frameSize = format.getFrameSize();
        float frameRate = format.getFrameRate();
        float durationInSeconds = (audioFileLength / (frameSize * frameRate));
    }

}

I want to make a method to select the starting playing point in the audio file (eg: start playing the file at 30 sec). That's why I wan't to retrieve the duration of my file.

When I do System.out.println(file); it prints the correct path of my file. However, since I am getting an error message, I'm obviously not doing something right.

I have already tried to find a solution online but I didn't find anything, so I posted here.

Thank you for your attention.


Solution

  • AudioSystem.getAudioInputStream throws these exceptions.

    These are checked exceptions so you must either use a try ... catch block to catch the exception or add a throws clause to the method declaration.

    A basic try ... catch would be:

    try
     {
       Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
       File file = new File(path + "/sample/loop1.wav");
    
       AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
    
       AudioFormat format = audioInputStream.getFormat();
    
       long audioFileLength = file.length();
       int frameSize = format.getFrameSize();
       float frameRate = format.getFrameRate();
       float durationInSeconds = (audioFileLength / (frameSize * frameRate));
     }
    catch (UnsupportedAudioFileException | IOException ex)
     {
       ex.printStackTrace();
     }