问题
I am trying to play partially downloaded file (I want the audio to start when it has enough downloaded data).
I have tried the following:
self.mutableData = nil;
self.mutableData = [NSMutableData data];
self.mutableData.length = 0;
GTMHTTPFetcher *fetcher =
[[self driveService].fetcherService fetcherWithURLString:song.filePath];
[fetcher setReceivedDataBlock:^(NSData *dataReceivedSoFar) {
[self.mutableData appendData:dataReceivedSoFar];
if (!self.audioPlayer.playing && self.mutableData.length > 1000000)
{
self.audioPlayer = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:self.mutableData error:nil];
[self.audioPlayer play];
}
}];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
if (error == nil)
{
NSLog(@"NSURLResponse: %@", fetcher.response.);
}
else
{
NSLog(@"An error occurred: %@", error);
}
}];
But it starts playing the first 1-3 seconds and then the app either crashes or it plays that 1-3 seconds over and over again until the download finishes and then it plays the whole song.
Can I somehow achieve this with AVPlayer
, or fix this problem?
回答1:
AVAudioPlayer cannot play files that are open for writing / downloading, but AVPlayer can. Switch to AVPlayer.
回答2:
To stream audio, you should use AVPlayer or Audio Queue Services.
initWithData
isn't intended for this purpose. You can use initWithData
after you have downloaded the entire file.
来源:https://stackoverflow.com/questions/18188156/playing-audio-file-while-i-download-it