简体   繁体   中英

ClassCastException when casting TargetDataLine

I have a program that records the mic for 5 sec and it should play it back after recording it, but an error occurs when casting it to my line. It occurs when a TargetDataLine is casted to a line.

code:

AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, false);
    
    DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
    final SourceDataLine sourceLine = (SourceDataLine)AudioSystem.getLine(info);
    sourceLine.open();
    
    info = new DataLine.Info(SourceDataLine.class, format);
    final TargetDataLine targetLine = (TargetDataLine)AudioSystem.getLine(info);
    targetLine.open();

error:

Exception in thread "main" java.lang.ClassCastException: class com.sun.media.sound.DirectAudioDevice$DirectSDL cannot be cast to class javax.sound.sampled.TargetDataLine (com.sun.media.sound.DirectAudioDevice$DirectSDL and javax.sound.sampled.TargetDataLine are in module java.desktop of loader 'bootstrap')

SDL has a write method and TDL has a read method. They have DataLine in common, but the divergence means you can't convert from one to the other, any more than you can cast an Dog (extends Animal) to a Cat (extends Animal).

Explanation of Class Cast Error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM