使用音轨类来为您完成这项工作。你可以做这样的事情。
JAVA端。
AudioTrack track;
int bufSize = AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
track = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufSize, AudioTrack.MODE_STREAM);
track.play();
while(true){
readBufferFromNative(); //update buffer from native code
....................
....................
}
在本机端:您需要首先读取帧并将其转换为原始 pcm 格式,然后开始连续填充音频缓冲区。当缓冲区满时,会自动播放。
JNIEXPORT int JNICALL Java_com_ffmpeg_Main_jniMainEntry(JNIEnv* env, jobject obj, jstring input) {
const char * pszFileName = (*env)->GetStringUTFChars(env, input, 0);
AVFormatContext * m_fc;
int err;
AVPacket pkt;
char * pAudioBuffer = (char *) av_malloc (AVCODEC_MAX_AUDIO_FRAME_SIZE * 2);
int i;
avcodec_register_all ();
avdevice_register_all ();
av_register_all ();
err = av_open_input_file(&m_fc, pszFileName, 0, 0, 0);
err = av_find_stream_info(m_fc);
for(i = 0; i<m_fc->nb_streams; i++) {
if((m_fc->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) || (m_fc->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
AVCodec *codec = avcodec_find_decoder(m_fc->streams[i]->codec->codec_id);
if (codec == 0)
continue;
err = avcodec_open(m_fc->streams[i]->codec, codec);
if (err <0)
continue;
}
}
while (av_read_frame(m_fc, &pkt)>= 0) {
if (m_fc-> streams[pkt.stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
int data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE * 2;
int size=pkt->size;
while(size > 0) {
int len = avcodec_decode_audio3(m_fc->streams[pkt.stream_index]->codec, (int16_t *) pAudioBuffer, &data_size, &pkt);
LOGD("data_size %d len %d", data_size, len);
size = pkt->size-len;
}
}
}
}