iOS StreamingKit如何录制/保存音频?

时间:2016-09-21 22:15:24

标签: ios iphone audio streaming avplayer

我正在使用https://github.com/tumtumtum/StreamingKit

用于流式传输实时网址。工作得非常好。我想在我的应用中添加录音/保存音频功能。有谁知道这个库是否可以做到这一点? 如果没有,还有其他选择吗?请注意,我需要录制LIVE流音频,而不是本地文件/静态URL。

该页面显示您可以在播放之前拦截PCM数据:

[audioPlayer appendFrameFilterWithName:@"MyCustomFilter" block:^(UInt32 channelsPerFrame, UInt32 bytesPerFrame, UInt32 frameCount, void* frames)
{
   ...
}];

但是,我不知道如何将其转换为实际的录制/ mp3文件,甚至不会截取实际数据?

1 个答案:

答案 0 :(得分:1)

你可以做这样的事情,虽然StreamingKit似乎对它给你的样本格式有点保密。什么是采样率?浮点数还是整数?我想你可以从样本量来猜测。此示例假设为16位整数。

NSURL *dstUrl = [[NSURL fileURLWithPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] ] URLByAppendingPathComponent:@"output.m4a"];

NSLog(@"write to %@", dstUrl);

__block AVAudioFile *audioFile = nil;

[audioPlayer appendFrameFilterWithName:@"MyCustomFilter" block:^(UInt32 channelsPerFrame, UInt32 bytesPerFrame, UInt32 frameCount, void* frames)
 {
     NSError *error;

     // what's the sample rate? StreamingKit doesn't seem to tell us
     double sampleRate = 44100;

     if (!audioFile) {
         NSDictionary *settings =
         @{
           AVFormatIDKey : @(kAudioFormatMPEG4AAC),
           AVSampleRateKey : @(sampleRate),
           AVNumberOfChannelsKey : @(channelsPerFrame),
           };

         // need commonFormat?
         audioFile = [[AVAudioFile alloc] initForWriting:dstUrl settings:settings commonFormat:AVAudioPCMFormatInt16 interleaved:YES error:&error];
         if (!audioFile) {
             // error
         }
     }

     AVAudioFormat *format = [[AVAudioFormat alloc] initWithCommonFormat:AVAudioPCMFormatInt16 sampleRate:sampleRate channels:channelsPerFrame interleaved:YES];
     AVAudioPCMBuffer *buffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:format frameCapacity:frameCount];

     buffer.frameLength = frameCount;
     memmove(buffer.int16ChannelData[0], frames, frameCount*bytesPerFrame);

     if (![audioFile writeFromBuffer:buffer error:&error]) {
         NSLog(@"write error: %@", error);
     }
}];

[self.audioPlayer performSelector:@selector(removeFrameFilterWithName:) withObject:@"MyCustomFilter" afterDelay:10];