我正在尝试在 android 中使用 ffmpeg 播放音频 mp3 文件,但我在下面提到的代码中遇到了问题
如何使用 ffmpeg 播放 mp3
void JNICALL Java_com_music_MainActivity_loadFile(JNIEnv* env, jobject obj,jstring file,jbyteArray array)
{
jboolean isfilenameCopy;
const char * filename = (*env)->GetStringUTFChars(env, file, &isfilenameCopy);
AVCodec *codec;
AVCodecContext *c= NULL;
int out_size, len;
FILE *f, *outfile;
uint8_t *outbuf;
uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
AVPacket avpkt;
jclass cls = (*env)->GetObjectClass(env, obj);
jmethodID play = (*env)->GetMethodID(env, cls, "playSound", "([BI)V");//At the begining of your main function
av_init_packet(&avpkt);
printf("Audio decoding\n");
__android_log_print(ANDROID_LOG_INFO, DEBUG_TAG, "inside load file");
/* find the mpeg audio decoder */
codec = avcodec_find_decoder(CODEC_ID_MP3);
if (!codec) {
fprintf(stderr, "codec not found\n");
exit(1);
}
c= avcodec_alloc_context();
/* open it */
if (avcodec_open(c, codec) < 0) {
fprintf(stderr, "could not open codec\n");
exit(1);
}
__android_log_print(ANDROID_LOG_INFO, DEBUG_TAG, "open avcode");
outbuf = malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
__android_log_print(ANDROID_LOG_INFO, DEBUG_TAG, "open %s",outbuf);
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "could not open %s\n", filename);
exit(1);
}
/* decode until eof */
avpkt.data = inbuf;
avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
__android_log_print(ANDROID_LOG_INFO, DEBUG_TAG, "data =%s and size %d",avpkt.data,avpkt.size);
while (avpkt.size > 0) {
out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
len = avcodec_decode_audio3(c, (short *)outbuf, &out_size, &avpkt);
__android_log_print(ANDROID_LOG_INFO, DEBUG_TAG, "length =%d",len);
if (len < 0) {
fprintf(stderr, "Error while decoding\n");
__android_log_print(ANDROID_LOG_INFO, DEBUG_TAG, " failed length =%d",errno);
exit(1);
}
if (out_size > 0) {
/* if a frame has been decoded, output it */
jbyte *bytes = (*env)->GetByteArrayElements(env, array, NULL);
memcpy(bytes, outbuf, out_size); //
(*env)->ReleaseByteArrayElements(env, array, bytes, 0);
(*env)->CallVoidMethod(env, obj, play, array, out_size);
}
avpkt.size -= len;
avpkt.data += len;
if (avpkt.size < AUDIO_REFILL_THRESH) {
/* Refill the input buffer, to avoid trying to decode
* incomplete frames. Instead of this, one could also use
* a parser, or use a proper container format through
* libavformat. */
memmove(inbuf, avpkt.data, avpkt.size);
avpkt.data = inbuf;
len = fread(avpkt.data + avpkt.size, 1,
AUDIO_INBUF_SIZE - avpkt.size, f);
if (len > 0)
avpkt.size += len;
}
}
fclose(f);
free(outbuf);
avcodec_close(c);
av_free(c);
}
我得到 len = - 1 in
len = avcodec_decode_audio3(c, (short *)outbuf, &out_size, &avpkt);
我究竟做错了什么??
请帮忙