I want to capture a part of live audio stream into a NSData file. I tried simply creating a NSData, but my application always stucks and NSData line, because source is continous. Is there any other way to create, an NSData or some array of ints from the internet radio signal?
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];
If the purpose of your data
object is to capture a portion of the audio stream, first remove this line entirely:
NSData *data = [NSData dataWithContentsOfURL:url];
As Anna Dickinson wrote in her comment, "NSData
represents a fixed-size block of memory" and since your data isn't fixed in this case, you'll have to store your data mutably instead.
In order to capture portions of the streaming audio data from the internet, do so separate of your AVPlayer
stream, and use the NSURLConnection
delegate methods instead to receive the data incrementally and asynchronously, for example:
...
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
}
And according to Apple's URL loading system programming guide, one nice thing about using an NSURLConnection, is that you can cancel the data stream at any time before connectionDidFinishDownloading:
is called so you can technically save as you go then cut off the stream and thus only save a portion of the audio by using [connection cancel];
. You can find more general info about NSURLConnection
in the docs.