Playing audio file while I download it

随声附和 提交于 2020-01-14 16:32:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!