从实时音频流创建NSData

时间:2014-11-16 18:32:07

标签: ios objective-c nsdata nsurl

我想将实时音频流的一部分捕获到NSData文件中。我试过简单地创建一个NSData,但我的应用程序总是卡住和NSData线,因为源是连续的。有没有其他方法可以创建一个NSData或一些来自互联网无线电信号的整数?

RadioInfo *sharedRadio = [RadioInfo sharedRadio];
NSString *program = [NSString stringWithFormat:@"%@",sharedRadio.list[value]];
NSURL *url = [NSURL URLWithString:program];

NSData *data = [NSData dataWithContentsOfURL:url];

AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
self.playerItem = [AVPlayerItem playerItemWithURL:url];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
self.player = [AVPlayer playerWithURL:url];
[self.player pause];
[self.player play];

1 个答案:

答案 0 :(得分:2)

如果data对象的目的是捕获音频流的一部分,请先完全删除此行:

NSData *data = [NSData dataWithContentsOfURL:url];

正如Anna Dickinson在她的评论中写道,“NSData表示一个固定大小的内存块”,并且由于您的数据在这种情况下不是固定的,因此您必须可变地存储数据 而不是。

为了从互联网捕获部分流式音频数据,请将AVPlayer流分开,并使用NSURLConnection委托方法代替以递增和异步方式接收数据,例如:

   ...

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                      cachePolicy:NSURLRequestReloadIgnoringCacheData
                                      timeoutInterval:30];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                   delegate:self startImmediately:NO];

    [connection scheduleInRunLoop:[NSRunLoop mainRunLoop] 
                  forMode:NSDefaultRunLoopMode];
    [connection start];
}

// Initialize the `data` here and store it as a mutable variable
- (void) connection:(NSURLConnection *)_connection didReceiveResponse:(NSURLResponse *)response {
    data = [NSMutableData data];
}

- (void) connection:(NSURLConnection *)_connection didReceiveData:(NSData *)_data {
    [data appendData:_data];

    // ** Potentially insert code here to save as you go ** 
}

- (void) connection:(NSURLConnection *)_connection didFailWithError:(NSError *)error {
    [self finish];
}

- (void)connectionDidFinishDownloading:(NSURLConnection *)_connection destinationURL:(NSURL *) destinationURL {
    [self finish];
}

- (void)finish {
    // Do whatever you want with the data
}

according to Apple's URL loading system programming guide,使用NSURLConnection的一个好处是,您可以在调用connectionDidFinishDownloading:之前随时取消数据流,这样您就可以在技术上保存,然后切断流因此只能使用[connection cancel];保存部分音频。您可以找到有关NSURLConnection in the docs.

的更多常规信息