Android MediaExtractor and mp3 stream

▼魔方 西西 提交于 2019-11-30 09:35:38

The code in onCreate() suggests you have a misconception about how MediaCodec works. Your code is currently:

onCreate() {
    ...setup...
    input();
    output();
}

MediaCodec operates on access units. For video, each call to input/output would get you a single frame of video. I haven't worked with audio, but my understanding is that it behaves similarly. You don't get the entire file loaded into an input buffer, and it doesn't play the stream for you; you take one small piece of the file, hand it to the decoder, and it hands back decoded data (e.g. a YUV video buffer or PCM audio data). You then do whatever is necessary to play that data.

So your example would, at best, decode a fraction of a second of audio. You need to be doing submit-input-get-output in a loop with proper handling of end-of-stream. You can see this done for video in the various bigflake examples. It looks like your code has the necessary pieces.

You're using a timeout of -1 (infinite), so you're going to supply one buffer of input and wait forever for a buffer of output. In video this wouldn't work -- the decoders I've tested seem to want about four buffers of input before they'll produce any output -- but again I haven't worked with audio, so I'm not sure if this is expected to work. Since your code is hanging I'm guessing it's not. It might be useful to change the timeout to (say) 10000 and see if the hang goes away.

I'm assuming this is an experiment and you're not really going to do all this in onCreate(). :-)

For anyone still looking for an answer to the problem of playing streamin audio reliably, you might want to have a look at this project (based on the MediaCodec API)

https://code.google.com/p/android-openmxplayer/

There are two issues with the above code. First, as the accepted answer states, only one read is done from the input stream. However, secondly, a call to .play() is needed on the AudioTrack.

This modification fixes OPs code:

mAudioTrack.play();

do {
    input();
    output();
} while (!sawInputEOS);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!