我有一个 NSArray 字符串,它们是 URL。数组中的每个 URL 都指向与歌曲的一部分相关联的数据。我可以使用以下代码播放完整歌曲,该代码将歌曲完全下载到单个文件中,然后从该文件中播放:
// Get file path to store song locally
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [NSString stringWithFormat:@"%@/temp.mp3", [paths objectAtIndex:0]];
// Remove current temp file and create a new one
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
if ([fileManager fileExistsAtPath:filePath]) [fileManager removeItemAtPath:filePath error:&error];
[fileManager createFileAtPath:filePath contents:nil attributes:nil];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
// Initialize loop variables
NSMutableData *songData = nil;
NSUInteger totalLength = 0;
NSString *localURLString = [NSString stringWithFormat:@"file://%@", [filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *localURL = [NSURL URLWithString:localURLString];
for (NSString *stringURL in urls) {
NSURL *url = [NSURL URLWithString:stringURL];
songData = [NSMutableData dataWithContentsOfURL:url];
totalLength += songData.length;
[fileHandle writeData:songData];
[fileHandle synchronizeFile];
}
[fileHandle closeFile];
self.player = [AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithURL:localURL]];
[self.player play];
现在我试图让整首歌曲无缝播放而无需先下载整个内容(所以基本上是流式传输,但不是从一个 URL 流式传输,我必须在流式传输时将多个歌曲拼凑在一起)。
我有什么选择?
更新 1:
我尝试生成清单文件,写入文件没有错误,并且清单字符串似乎格式正确,但播放器不播放。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *manifestPath = [NSString stringWithFormat:@"%@/manifest.m3u8", [paths objectAtIndex:0]];
NSMutableString *manifestString = [[NSMutableString alloc] init];
[manifestString appendString:@"#EXTM3\n"];
for (NSString *stringURL in urls) {
[manifestString appendFormat:@"%@\n", stringURL];
}
[manifestString appendString:@"#EXT-X-ENDLIST"];
NSError *err = nil;
[manifestString writeToFile:manifestPath atomically:YES encoding:NSUTF8StringEncoding error:&err];
if (err) {
NSLog(@"error writing manifest: %@", err);
}
NSString *manifestURLString = [NSString stringWithFormat:@"file://%@", [filePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *manifestURL = [NSURL URLWithString:manifestURLString];
self.player = [AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithURL:manifestURL]];
[self.player play];