说在前面的是,我用的mp4v2版本是mp4v2-2.2.0,与之前版本相比接口函数稍有不同!
1. 首先调用MP4CreateEx()函数,创建输出的MP4文件
MP4FileHandle file = MP4CreateEx("test.mp4", 0, 1, 1, "isom", 0x00000200, p, 4);
2. 接下来设置timescale
MP4SetTimeScale(file, 90000);
3. 接下来添加video track
MP4TrackId video = MP4AddH264VideoTrack(file, 90000, 90000/25, 640, 480,
0x4d, //sps[1] AVCProfileIndication
0x40, //sps[2] profile_compat
0x1f, //sps[3] AVCLevelIndication
3); // 4 bytes length before each NAL unit
MP4SetVideoProfileLevel(file, 0x7F);
4. 接下来添加audio track
MP4TrackId audio = MP4AddAudioTrack(file, 16000, 1024, MP4_MPEG4_AUDIO_TYPE);
MP4SetAudioProfileLevel(file, 0x2);
5. 现在创建工作结束了,之后就是循环写入video和audio数据,写video和audio的函数分别是
MP4WriteSample(file, video, buf, size, MP4_INVALID_DURATION, 0, 1);
MP4WriteSample(file, audio, buf, size, MP4_INVALID_DURATION, 0, 1);
6. 接下来需要为video添加SPS和PPS信息
MP4AddH264SequenceParameterSet(file, video, sps_pps, 10);
MP4AddH264PictureParameterSet(file, video, sps_pps+10, 4);
7.最后遍历为MP4添加索引
MP4Close(file, 0);
以上为mp4库的调用流程,video和audio的buf需要自己写测试函数传进来,SPS和PPS需要预先知道。
int aa(void)
{
unsigned char sps_pps[14] = {0x67, 0x4d, 0x40, 0x1F, 0x96 ,0x54, 0x05, 0x01, 0xec, 0x80, 0x68, 0xce, 0x38, 0x80};
char *p[4];
p[0] = "isom";
p[1] = "iso2";
p[2] = "avc1";
p[3] = "mp41";
MP4FileHandle file = MP4CreateEx("test.mp4", 0, 1, 1, "isom", 0x00000200, p, 4);
if (file == MP4_INVALID_FILE_HANDLE)
{
printf("open file fialed.
");
return;
}
MP4SetTimeScale(file, 90000);
//添加h264 track
MP4TrackId video = MP4AddH264VideoTrack(file, 90000, 90000/25, 640, 480,
0x4d, //sps[1] AVCProfileIndication
0x40, //sps[2] profile_compat
0x1f, //sps[3] AVCLevelIndication
3); // 4 bytes length before each NAL unit
if (video == MP4_INVALID_TRACK_ID)
{
printf("add video track failed.
");
return;
}
MP4SetVideoProfileLevel(file, 0x7F);
//添加aac音频
MP4TrackId audio = MP4AddAudioTrack(file, 16000, 1024, MP4_MPEG4_AUDIO_TYPE);
if (video == MP4_INVALID_TRACK_ID)
{
printf("add audio track failed.
");
return;
}
MP4SetAudioProfileLevel(file, 0x2);
while(mp4_read_h264_frame(fpMjpeg, buf, MP4_BUF_SIZE, &size) != -1)
{
buf[0] = ((size-4) & 0xff000000) >> 24;
buf[1] = ((size-4) & 0x00ff0000) >> 16;
buf[2] = ((size-4) & 0x0000ff00) >> 8;
buf[3] = (size-4) & 0x000000ff;
MP4WriteSample(file, video, buf, size, MP4_INVALID_DURATION, 0, 1);
}
while(-1 != mp4_read_aac_frame(fpPcm, buf, MP4_BUF_SIZE, &size))
{
MP4WriteSample(file, audio, buf, size, MP4_INVALID_DURATION, 0, 1);
}
MP4AddH264SequenceParameterSet(file, video, sps_pps, 10);
MP4AddH264PictureParameterSet(file, video, sps_pps+10, 4);
MP4Close(file, 0);
return 0;
}