前言
VideoToolbox硬編碼H.264
使用AudioToolbox編碼AAC
在上一篇中,介紹了如何從麥克風(fēng)采集聲音并用AudioToolbox編碼成AAC碼流,這次是使用AudioToolbox來播放之前錄制的AAC碼流。
介紹
在iOS設(shè)備上播放音頻,可以使用AVAudioPlayer(AVFoundation框架內(nèi)),但是不支持流式播放。
Apple recommends that you use this class for audio playback unless you are playing audio captured from a network stream or require very low I/O latency.
本文嘗試兩種播放方式:
- 使用
AudioServicesPlaySystemSound(音頻小于等于30s); - 使用Audio Queue Services音頻隊列;
Guide
AAC碼流結(jié)構(gòu)圖
AAC原始碼流(又稱為“裸流”)是由一個一個的ADTS frame組成的。他們的結(jié)構(gòu)如下圖所示。

了解AAC的碼流結(jié)構(gòu),對Audio Queue Services的參數(shù)設(shè)置更清晰。
具體實現(xiàn)
1、使用AudioServicesPlaySystemSound
AudioServicesCreateSystemSoundID創(chuàng)建系統(tǒng)聲音
AudioServicesAddSystemSoundCompletion設(shè)置回調(diào)
AudioServicesPlaySystemSound開始播放
- (void)onClick:(UIButton *)button {
[self.mButton setHidden:YES];
NSURL *audioURL=[[NSBundle mainBundle] URLForResource:@"abc" withExtension:@"aac"];
SystemSoundID soundID;
//Creates a system sound object.
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(audioURL), &soundID);
//Registers a callback function that is invoked when a specified system sound finishes playing.
AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, &playCallback, (__bridge void * _Nullable)(self));
// AudioServicesPlayAlertSound(soundID);
AudioServicesPlaySystemSound(soundID);
}
- (void)onPlayCallback {
[self.mButton setHidden:NO];
}
以下是API的限制
- No longer than 30 seconds in duration
- In linear PCM or IMA4 (IMA/ADPCM) format
- Packaged in a .caf, .aif, or .wav file
雖然AAC音頻不在支持列表里面,但是經(jīng)過測試,播放是可以的。
2、使用Audio Queue Services音頻隊列
Audio Queue Services的播放步驟如下:
1,給buffer填充數(shù)據(jù),并把buffer放入就緒的buffer queue;
2,應(yīng)用通知隊列開始播放;
3、隊列播放第一個填充的buffer;
4、隊列返回已經(jīng)播放完畢的buffer,并開始播放下面一個填充好的buffer;
5、隊列調(diào)用之前設(shè)置的回調(diào)函數(shù),填充播放完畢的buffer;
6、回調(diào)函數(shù)中把buffer填充完畢,并放入buffer queue中。
遇到的問題
問題1:malloc錯誤
malloc: *** error for object 0x154e58498: incorrect checksum for freed object - object was probably modified after being freed.
Set a breakpoint in malloc_error_break to debug.
問題2:selector調(diào)用錯誤
Method cache corrupted. This may be a message to an invalid object, or a memory error somewhere else.
objc[12730]: receiver 0x13fe1d4f0, SEL 0x10004e2d8, isa 0x100051828, cache 0x100051838, buckets 0x13fd86650, mask 0x7, occupied 0x1
objc[12730]: receiver 112 bytes, buckets 128 bytes
objc[12730]: selector 'fillBuffer:'
objc[12730]: isa 'AACPlayer'
objc[12730]: Method cache corrupted.
這兩個問題是出現(xiàn)在AudioQueueAllocateBuffer方法和fillBuffer的調(diào)用,而且是時而正常,時而崩潰。
先查看參數(shù)是否正確,通過xcode的debug工具,我們可以看到以下的數(shù)據(jù):
(AudioStreamBasicDescription) $0 = {
mSampleRate = 44100
mFormatID = 1633772320
mFormatFlags = 0
mBytesPerPacket = 0
mFramesPerPacket = 1024
mBytesPerFrame = 0
mChannelsPerFrame = 1
mBitsPerChannel = 0
mReserved = 0
}
maxSize = 768
packetNums = 85
(mStartOffset = 0, mVariableFramesInPacket = 0, mDataByteSize = 23)
AudioStreamBasicDescription的參數(shù)很熟悉,因為就是我們上一篇的編碼所設(shè)置的參數(shù)。
AudioQueueAllocateBuffer的參數(shù)audioQueue、buffer_size、audioBuffers都很正常,暫時排除存在問題的可能性。
fillBuffer方法中,有AudioFileReadPackets和AudioQueueEnqueueBuffer兩個方法。AudioQueueEnqueueBuffer是把buffer放入到AudioQueue,參數(shù)檢查沒有問題。初步判斷是AudioFileReadPackets存在問題。
通過多次調(diào)試,發(fā)現(xiàn)AudioFileReadPackets在偶然情況下回返回-60的情況,這時會導(dǎo)致崩潰。
通過google查到-60對應(yīng)的是kAudioFilePositionError,回來檢查AudioFileReadPackets的參數(shù),發(fā)現(xiàn)參數(shù)沒有初始化,每次調(diào)用的參數(shù)都不同。
查API文檔知道AudioFileReadPackets的參數(shù)除了audioFileID和cache、packet長度,均為傳入?yún)?shù),參數(shù)是否初始化并不會影響。至此,fillBuffer方法的線索斷了。
回顧了一下整體的流程,決定從malloc錯誤入手,在so上找到以下解釋。
- you are freeing an object twice,
- you are freeing a pointer that was never allocated
- you are writing through an invalid pointer which previously pointed to an object which was already freed
內(nèi)存訪問越界,怎么會和selector調(diào)用錯誤扯上關(guān)系?百思不得其解。
最后,幾經(jīng)波折終于找到罪魁禍?zhǔn)?。就是以下這行代碼:
audioStreamPacketDescrption = malloc(sizeof(audioStreamPacketDescrption) * packetNums);
當(dāng)我打過一次audioStreamPacketDescrption,再打AudioStreamPacketDescrption的時候,Xcode會自動索引為audioStreamPacketDescrption,導(dǎo)致sizeof會計算出不同的大小。
PS:按理說對一個結(jié)構(gòu)體的類和結(jié)構(gòu)體的實例進(jìn)行sizeof,應(yīng)該是一樣的大?。ú凰銊討B(tài)分配)。
這個并沒有錯,可是為了方便我把a(bǔ)udioStreamPacketDescrption定義成指針了!
兩個教訓(xùn):
1、不要起和類名一樣的變量;
2、指針和實例的區(qū)別要從名字即可分清;
總結(jié)
播放比解碼容易多,Audio Queue Services的使用就參照demo和上圖的6個步驟,可以很清晰看懂,就不贅述。
順便提一下,之前錄制的aac音頻和h264可以很方便的打包成mp4!看下圖:

只需簡單的一行指令:
ffmpeg -i abc.h264 -i abc.aac -vcodec copy -f mp4 abc.mp4
