最后还是再StackOverFlow上找到的解决办法,StackOverFlow,大赞!!
从麦克风获取PCM数据的方法,参看Apple的官方例子:SpeakHere
注意,以下方法实现的前提是:
录音格式为kAudioFormatLinearPCM;
录音格式的mBitsPerChannel要设置为16
SpeakHere的InputBufferHandler回调方法中,可以获取到PCM数据:
通过[recorder.mp3Encoder encodePcmData:inBuffer->mAudioData withDataSize:inNumPackets];
把PCM数据扔给MP3编码器
之前在BaiDu上搜了一些文章,都是把PCM文件转成MP3文件的,所用的方法是lame_encode_buffer_interleaved
而且传递数据长度的参数,用的是inBuffer->mAudioDataByteSize
也许转换文件用这个方法可以,也有可能是PCM的格式问题,用这个方法编码出来的数据,有问题,爆音,而且,声音断断续续
在StackOverFlow上找到的方法,用的数据长度参数是inNumPackets,编码方法是lame_encode_buffer
结果大不相同!
我为人人,人人为我!
从麦克风获取PCM数据的方法,参看Apple的官方例子:SpeakHere
注意,以下方法实现的前提是:
录音格式为kAudioFormatLinearPCM;
录音格式的mBitsPerChannel要设置为16
SpeakHere的InputBufferHandler回调方法中,可以获取到PCM数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
// AudioQueue callback function, called when an input buffers has been filled.
void
AudioInputBufferHandler(
void
* inUserData,
AudioQueueRef inAQ,
AudioQueueBufferRef inBuffer,
const
AudioTimeStamp * inStartTime,
UInt32 inNumPackets,
const
AudioStreamPacketDescription * inPacketDesc ) {
AudioRecorder *recorder = (AudioRecorder *)inUserData;
try
{
if
( recorder.isRunning && inNumPackets > 0 ) {
[recorder.mp3Encoder encodePcmData:inBuffer->mAudioData withDataSize:inNumPackets];
// write packets to file
/*
XThrowIfError( AudioFileWritePackets( aqr->mRecordFile,
FALSE,
inBuffer->mAudioDataByteSize,
inPacketDesc,
aqr->mRecordPacket,
&inNumPackets,
inBuffer->mAudioData ),
"AudioFileWritePackets failed!");
aqr->mRecordPacket += inNumPackets;
*/
}
// if we're not stopping, re-enqueue the buffe so that it gets filled again
if
( recorder.isRunning ) {
XThrowIfError( AudioQueueEnqueueBuffer( inAQ, inBuffer, 0,
NULL
), @
"AudioQueueEnqueueBuffer failed!"
);
}
}
catch
(
NSException
*e ) {
[Dialog simpleToast:[
NSString
stringWithFormat:@
"Error: %@ (%@)\n"
, [e name], [e reason]]];
// DLog(@"Error: %@ (%@)\n", [e name], [e reason]);
}
}
|
通过[recorder.mp3Encoder encodePcmData:inBuffer->mAudioData withDataSize:inNumPackets];
把PCM数据扔给MP3编码器
1
2
3
4
5
6
7
8
9
10
11
|
- (
void
)encodePcmData:(
void
*)pcmBuffer withDataSize:(UInt32)pcmDataSize {
int
mp3DataSize = pcmDataSize * 4;
unsigned
char
mp3Buffer[mp3DataSize];
int
encodedBytes = lame_encode_buffer( lame, pcmBuffer, pcmBuffer, pcmDataSize, mp3Buffer, mp3DataSize );
//lame_encode_buffer_interleaved( lame, pcmBuffer, PCM_DATA_SIZE, mp3Buffer, MP3_DATA_SIZE );
NSData
*mp3Data = [
NSData
dataWithBytes:&mp3Buffer length:encodedBytes];
}
|
之前在BaiDu上搜了一些文章,都是把PCM文件转成MP3文件的,所用的方法是lame_encode_buffer_interleaved
而且传递数据长度的参数,用的是inBuffer->mAudioDataByteSize
也许转换文件用这个方法可以,也有可能是PCM的格式问题,用这个方法编码出来的数据,有问题,爆音,而且,声音断断续续
在StackOverFlow上找到的方法,用的数据长度参数是inNumPackets,编码方法是lame_encode_buffer
结果大不相同!
我为人人,人人为我!