我想从谷歌驱动器流式传输音频文件,从谷歌驱动器 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");
}