由於與我的問題無關的原因,我必須執行AVPlayer
播放AVURLAssets
使用自定義AVAssetResourceLoader
。總的來說我的實現效果很好,但通過AirPlay
試圖外部播放時(不鏡像):AVAssetResourceLoader支持AVURLAsset播放只能通過AirPlay播放失敗
self.player.allowsExternalPlayback = YES;
self.player.usesExternalPlaybackWhileExternalScreenIsActive = YES;
播放失敗,並在AppleTV
的錯誤信息,並通過AVPlayerItemFailedToPlayToEndTimeNotification
發佈錯誤消息。
我可以用簡單的實現本地媒體文件(包含在App Bundle中)的請求數據的簡單AVAssetResourceLoader
實現重現相同的問題。這是我的實現:
- (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest; {
AVAssetResourceLoadingDataRequest *dataRequest = loadingRequest.dataRequest;
AVAssetResourceLoadingContentInformationRequest *contentRequest = loadingRequest.contentInformationRequest;
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"localfile" withExtension:@"mov"];
if (contentRequest)
{
NSString *extension = [fileURL pathExtension];
NSString *contentTypeString = (NSString*)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,(CFStringRef)extension,NULL);
contentRequest.contentType = contentTypeString;
contentRequest.contentLength = [[[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil] fileSize];
contentRequest.byteRangeAccessSupported = YES;
}
if (dataRequest)
{
NSInteger length = [dataRequest requestedLength];
if (length>1024*1024*20)
{
// limiting to 20MB here because iOS sometimes requests the whole file which would not fit in memory
length = 1024*1024*20;
}
NSFileHandle *fh = [NSFileHandle fileHandleForReadingFromURL:fileURL error:nil];
[fh seekToFileOffset:[dataRequest requestedOffset]];
NSData *fileData = [fh readDataOfLength:length];
[dataRequest respondWithData:fileData];
[fh closeFile];
}
[loadingRequest finishLoading];
return YES;}
此代碼直接在設備上播放。如果啓用了AirPlay,則會使用內容和數據請求調用資源加載器大約4-5次,請求該項目的前8kb。回調然後停止,最終我在Apple TV和幾個AVPlayerItemFailedToPlayToEndTimeNotifications
上收到錯誤消息。第一個通知包含「媒體不支持」錯誤。
(通過將同一片媒體添加到AVPlayer
作爲基於正常文件的項目,通過AirPlay
也可以正常播放)。
任何輸入將不勝感激,謝謝!
好的感謝您的建議。 – iBhavin
經過一些更多的測試後,我發現使用上面的代碼,音頻資產可以通過AirPlay播放。因此,我認爲視頻播放失敗的行爲可能是AVFoundation或AppleTV中的一個錯誤。 – freeridecoding