很抱歉,如果这似乎是一个简单的问题,但这是我第一次在编程中试验声音。
我在这里想要实现的是将通过TargetDataLine对象获得的数据编码为.ogg文件。我的出发点是官方Java文档https://docs.oracle.com/javase/tutorial/sound/capturing.html。
我正在使用JavaZoom的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();
}
}
使用此代码,我在控制台中获得以下输出。
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)
我已尝试将enconding更改为VorbisEncoding.PCM_SIGNED
,但随后控制台会抛出以下错误。
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)