Search code examples
javaencodingjavasound

Encoding TargetDataLine data into Ogg Vorbis file


Sorry if this seems like a straightforward question but it's my very first time experimenting with sound in programming.

What I'm trying to achieve here is to encode the data obtained through a TargetDataLine object into a .ogg file. My starting point was the official Java Documentation https://docs.oracle.com/javase/tutorial/sound/capturing.html.

I'm using JavaZoom's Vorbis API http://www.javazoom.net/vorbisspi/vorbisspi.html.

private static void recordAudio(int id) {

    Map<String, Object> myMap = new HashMap<String, Object>();
    myMap.put("duration", 0);
    myMap.put("title", "title_test");
    myMap.put("author", "author_test");
    myMap.put("album", "album_test");
    myMap.put("date", "date_test");
    myMap.put("copyright", "copyright_test");
    myMap.put("comment", "comment_test");

    VorbisAudioFormat format = new VorbisAudioFormat(VorbisEncoding.VORBISENC, 48000.F, 16, 2, 4, 48000.F, true, myMap);
    Mixer mixer = AudioSystem.getMixer(AudioSystem.getMixerInfo()[id]);

    TargetDataLine line;
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
    if (!AudioSystem.isLineSupported(info)) {
        System.out.println("Line is not supported.");
    }
    try {
        line = (TargetDataLine) mixer.getLine(info);
        line.open(format);
        line.start();

        AudioInputStream ais = new AudioInputStream(line);
        File auFile = new File("path/stream_test.ogg");
        AudioFileFormat.Type fileType = VorbisFileFormatType.OGG;
        AudioSystem.write(ais, fileType, auFile);

    } catch (LineUnavailableException ex) {
        System.out.println("Line is unavailable.");
        ex.printStackTrace();
    } catch (FileNotFoundException e) {
        System.out.println("File not found.");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

With this code I'm getting the following output in console.

Line is not supported.
Exception in thread "main" java.lang.IllegalArgumentException: Line unsupported: interface TargetDataLine supporting format VORBISENC 48000.0 Hz, 16 bit, stereo, 4 bytes/frame, 
    at com.sun.media.sound.DirectAudioDevice.getLine(Unknown Source)
    at test_mixer.Main.recordAudio(Main.java:60)
    at test_mixer.Main.main(Main.java:35)

I've tried changing the enconding to VorbisEncoding.PCM_SIGNED but then the console throws the following error.

Exception in thread "main" java.lang.IllegalArgumentException: could not write audio file: file type not supported: OGG
at javax.sound.sampled.AudioSystem.write(Unknown Source)
at test_mixer.Main.recordAudio(Main.java:66)
at test_mixer.Main.main(Main.java:35)

Solution

  • The Vorbis SPI code you are using is based on the JOrbis Ogg decoder.

    It only supports reading Ogg files, it does not support encoding and writing Ogg files.