我正在使用this api,並遇到了一些令我困惑的代碼示例。我知道我可以使用「new」將對象分配給接口,因爲接口是數據類型。我從下面的代碼中不理解的是爲什麼變量:「cc」和「audioDecoder」被分配了它們已經分配的值。據我所知,這些變量應該分配給新的對象。有人能解釋這裏發生了什麼嗎?爲什麼這些接口類型的變量沒有被用來實例化新對象?
try {
// open media file
DefaultMediaPlayer player = new DefaultMediaPlayer("/home/me/walking.wav");
// get some properties of the first audio stream
IDecoder audioDecoder = player.getAudioStreamDecoder(0);
ICodecContextWrapper cc = audioDecoder.getCodecContext();
int sampleFormat = cc.getSampleFormat();
int sampleRate = cc.getSampleRate();
int bytesPerSample = AVSampleFormat.getBytesPerSample(sampleFormat);
long channelLayout = cc.getChannelLayout();
int channelCount = AVChannelLayout.getChannelCount(channelLayout);
AudioFormat.Encoding encoding;
if (AVSampleFormat.isPlanar(sampleFormat) || AVSampleFormat.isReal(sampleFormat))
throw new LibavException("unsupported output sample format");
else if (AVSampleFormat.isSigned(sampleFormat))
encoding = AudioFormat.Encoding.PCM_SIGNED;
else
encoding = AudioFormat.Encoding.PCM_UNSIGNED;
// create Java InputStream for audio stream raw data
SampleInputStream sis = new SampleInputStream(sampleRate * bytesPerSample * channelCount, true);
// create AudioInputStream from the SampleInputStream
AudioInputStream audioStream = new AudioInputStream(sis, new AudioFormat(encoding, sampleRate,
bytesPerSample * 8, channelCount, bytesPerSample * channelCount, sampleRate,
ByteOrder.BIG_ENDIAN.equals(ByteOrder.nativeOrder())), -1);
// create adapter between Libav audio frames and the SampleInputStream
Frame2AudioFrameAdapter resampler = new Frame2AudioFrameAdapter(channelLayout, channelLayout, sampleRate,
sampleRate, sampleFormat, sampleFormat);
// get audio mixer for the audio stream format
PlaybackMixer audioMixer = PlaybackMixer.getMixer(audioStream.getFormat());
// connect all streams
audioDecoder.addFrameConsumer(resampler);
resampler.addAudioFrameConsumer(sis);
audioMixer.addInputStream(audioStream);
// enable audio stream decoding
player.setAudioStreamDecodingEnabled(0, true);
// start playback
audioMixer.play();
player.play();
// wait until the playback stops
player.join();
// release system resources
player.close();
resampler.dispose();
PlaybackMixer.closeAllMixers();
} catch (Exception ex) {
Logger.getLogger(PlaybackSample.class.getName()).log(Level.WARNING, "unable to play audio", ex);
}
你的問題讓我困惑,我不理解的代碼是什麼上面迷惑你。 cc和audioDecoder似乎分配給合法對象。澄清的要點:由於裸接口沒有實現,你不能創建一個新的SomeInterface()對象。唯一的方法是使用從接口創建的匿名內部類。 –
我也有點失落 - 這些調用的結果被分配給有效的引用;有什麼問題?變量不需要分配新的對象,只需要對象:'Foo foo = new Foo(); Foo foo2 = foo;' –