3

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?

P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
vburojevic
  • 1,666
  • 5
  • 24
  • 34
  • Did you find a solution ? I have a stream of `Data` to play before download finishes but I can't figure it out. xD – nverinaud Oct 14 '21 at 14:39

2 Answers2

1

AVAudioPlayer cannot play files that are open for writing / downloading, but AVPlayer can. Switch to AVPlayer.

user12679
  • 11
  • 1
  • 1
  • This answer is lacking in details, but I don't think it warrants deletion... it is better than nothing, isn't it? – ArtOfWarfare Oct 07 '14 at 02:27
  • @ArtOfWarfare There isn't nothing though. It's a poor quality copy of the other answer posted a year beforehand! – worldofjr Oct 07 '14 at 07:31
0

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.

Marcus Adams
  • 53,009
  • 9
  • 91
  • 143
  • Ok I know, but what if I cannot obtain a direct link to stream? This is the problem with google drive, so my other solution is to start download to device, and then start playing from it. Do you have any advice? – vburojevic Aug 12 '13 at 14:14