AVAudioPlayer从缓冲区播放

时间:2013-08-13 10:12:37

标签: iphone ios ipad download avaudioplayer

我想从谷歌驱动器流式传输音频文件,谷歌驱动器sdk的唯一方法是我可以跟踪下载的是[fetcher setReceivedDataBlock:^(NSData *dataReceivedSoFar),所以我实现了类似的东西,但我不太确定是一个很好的解决方案,所以我向你们提出建议。

好的,因为我只能获得dataReceivedSoFar,我将从中删除已下载的数据,然后将新数据附加到已保存的数据,并在数据长度为AVAudioPlayer时开始播放大于100 000字节。

请告诉我这是否是一个很好的解决方案,如果你有一些建议。

代码:

GTMHTTPFetcher *fetcher =
        [[self driveService].fetcherService fetcherWithURLString:song.filePath];

    NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesDir    = [myPathList  objectAtIndex:0];
    NSString *songPath = [[NSString alloc] initWithString: [cachesDir stringByAppendingPathComponent:[NSString stringWithFormat:@"Song.%@", [song.name pathExtension]]]];

    [fetcher setReceivedDataBlock:^(NSData *dataReceivedSoFar) {

        NSFileManager *filemgr;
        filemgr = [NSFileManager defaultManager];
        if (![filemgr fileExistsAtPath: songPath ] == YES)
            [filemgr createFileAtPath:songPath contents:nil attributes:nil];

        NSData *currentData = [NSData dataWithContentsOfFile:songPath];
        NSLog(@"LENGTH: %d", currentData.length);

        NSMutableData *mutableData = [NSMutableData dataWithData:dataReceivedSoFar];

        if (currentData.length > 0) {
            [mutableData replaceBytesInRange:NSMakeRange(0, [currentData length]) withBytes:NULL length:0];
        }


        NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:songPath];
        [handle seekToEndOfFile];
        [handle writeData:mutableData];
        //[handle synchronizeFile];
        [handle closeFile];

        if (!self.audioPlayer.playing && dataReceivedSoFar.length > 100000)
        {
            NSURL *URL = [NSURL fileURLWithPath:songPath];

            self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:URL error:nil];
            [self.audioPlayer play];
            NSLog(@"Audio player started playing");
        }

0 个答案:

没有答案