示例代码: XBVoiceTool
所需基础:
分析:
前面讲过如何播放PCM数据,现在我们需要的就是把MP3或者AAC格式的数据转成PCM数据,提供给Player进行播放。
引入几个新的内容:
ExtAudioFileRef :代表所读取的音频。可以用 ExtAudioFileOpenURL 创建
ExtAudioFileSetProperty :设置 ExtAudioFileRef 的属性
ExtAudioFileRead :从 ExtAudioFileRef 读取数据
关键代码:
1.读取音频
NSURL *url = [NSURL fileURLWithPath:filePath];
CheckError(ExtAudioFileOpenURL((__bridge CFURLRef)url, &_audioFile),"打开文件失败");
2.设置 _audioFile 转换出来的音频流格式信息(即从_audioFile读取到的音频流格式)
uint size = sizeof(_outputFormat);
CheckError(ExtAudioFileSetProperty(_audioFile, kExtAudioFileProperty_ClientDataFormat, size, &_outputFormat), "setkExtAudioFileProperty_ClientDataFormat failure");
3.调用ExtAudioFileRead ,从 _audioFile 读取数据,并赋值给Player
_player.bl_inputFull = ^(XBAudioUnitPlayer *player, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) {
strongSelf->_bufferList->mBuffers[0].mDataByteSize = CONST_BUFFER_SIZE;
OSStatus status = ExtAudioFileRead(strongSelf->_audioFile, &inNumberFrames, strongSelf->_bufferList);
memcpy(ioData->mBuffers[0].mData, strongSelf->_bufferList->mBuffers[0].mData, strongSelf->_bufferList->mBuffers[0].mDataByteSize);
ioData->mBuffers[0].mDataByteSize = strongSelf->_bufferList->mBuffers[0].mDataByteSize;
if (ioData->mBuffers[0].mDataByteSize == 0)
{
[weakSelf stop];
}
strongSelf->_readedFrame += ioData->mBuffers[0].mDataByteSize / strongSelf->_outputFormat.mBytesPerFrame;
CheckError(status, "转换格式失败");
if (inNumberFrames == 0) NSLog(@"播放结束");
NSLog(@"%f",[strongSelf getProgress]);
};
网友评论