iOS StreamingKit 如何record/save 音频?

iOS StreamingKit how to record/save the audio?

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

用于直播 url。工作得很好。我想在我的应用程序中添加 recording/save 的音频功能。有谁知道这个图书馆是否可以做到这一点? 如果没有,还有其他选择吗?请注意,我需要录制实时流媒体音频,而不是本地文件/静态文件 url.

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

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

但是,我不确定如何将其转换为实际的录音/mp3 文件,甚至无法从中截取实际数据?

你可以做这样的事情,尽管 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];