嘗試使用 NSString stringWithContentsOfFile 讀取視頻文件路徑並傳給 MPMoviePlayerViewController,結果 contentPath 始終為 null,導致播放失敗。
stringWithContentsOfFile 用於讀取文本文件內容(如 JSON、HTML),而非獲取文件路徑。視頻文件(.mov, .mp4)是二進制數據,無法以文本編碼讀取。正確做法是直接使用文件路徑構建 NSURL。
- (void)playVideo {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"video2.MOV"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath]; // 關鍵:使用 fileURLWithPath
MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:fileURL];
[self presentMoviePlayerViewControllerAnimated:playerVC];
[playerVC.moviePlayer play];
}
若視頻打包在應用內(非沙盒),請使用:
NSString *path = [[NSBundle mainBundle] pathForResource:@"video2" ofType:@"mov"];
NSURL *url = [NSURL fileURLWithPath:path];
AVPlayerViewController(iOS 8+)替代已棄用的 MPMoviePlayerViewController。[[NSFileManager defaultManager] fileExistsAtPath:filePath]。