简体   繁体   English

使用AVPlayer和AVPlayerViewController,但不存在音频和视频

[英]Using AVPlayer and AVPlayerViewController, but audio and video not present

My code looks like this: 我的代码如下所示:

_player = [AVPlayer playerWithURL:destination];
_playerVC = [AVPlayerViewController new];
_playerVC.player = _player;
dispatch_async(dispatch_get_main_queue(), ^{
    [self presentViewController:_playerVC animated:YES completion:^{
        [_player play];
    }];
});

_player represents AVPlayer and _playerVC represents AVPlayerViewController. _player代表AVPlayer,_playerVC代表AVPlayerViewController。 I have strong global references to these objects. 我对这些对象有很强的全局引用。

Using terminal, I played the file located at the destination (open -a quicktime\\ player destinationURLAbsoluteString) and saw the file is properly loaded since it was playing. 使用终端,我播放了位于目标位置的文件(打开-a quicktime \\播放器destinationURLAbsoluteString),并看到文件自播放以来已正确加载。

It is a m4v file. 这是一个m4v文件。 I have played a m4a file and it properly gave me audio. 我播放了一个m4a文件,它正确地给了我音频。 I have also substituted the url I have for destination to some remote url and that worked for video. 我也将目的地的网址替换为一些远程网址,该网址适用于视频。 This leads me to believe it has something to do with my video. 这使我相信,这与我的视频有关。 What's weird is that my AVPlayerViewController does show a black screen with all the normal controls, and even shows the video is 2 minutes and 23 seconds. 奇怪的是,我的AVPlayerViewController确实显示了带有所有正常控件的黑屏,甚至显示视频是2分23秒。 Upon opening the video file manually, I can see that it is also 2 minutes and 23 seconds. 手动打开视频文件后,我看到它也是2分23秒。

I can forward through the video properly by dragging the white dot indicative of the video's position, but I never hear anything, nor do I see anything but the black screen and controls. 我可以通过拖动指示视频位置的白点来正确地浏览视频,但是除了黑屏和控件外,我什么也听不到。

TL;DR TL; DR

NSLog(@"Destination: %@",destination); NSLog(@“ Destination:%@”,destination); prints: file:///Users/MyLogin/Library/Developer/CoreSimulator/Devices/694F4C94-F785-4931-A312-4C3E7DE8673A/data/Containers/Data/Application/76C923BE-5B25-41F7-9145-63414657FDF6/Documents/mzvf_5914002519860647075.640x352.h264lc.D2.p.m4v 打印:file:/// Users / MyLogin / Library / Developer / CoreSimulator / Devices / 694F4C94-F785-4931-A312-4C3E7DE8673A / data / Containers / Data / Application / 76C923BE-5B25-41F7-9145-63414657FDF6 / Documents / mzvf_591400251986064707 .640x352.h264lc.D2.p.m4v

All in all, it looks like I'm properly retrieving the video, but for some reason my player controller is completely black and void of audio. 总而言之,看起来我正在正确检索视频,但是由于某种原因,我的播放器控制器完全是黑色的,没有音频。 Any help is much appreciated. 任何帮助深表感谢。

Source Code: 源代码:

.m file: .m文件:

#import "ViewController.h"
#import "View2ViewController.h"

#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>



@interface ViewController ()
@property NSDictionary *requestedSong;
@property (strong) AVPlayer *player;  //Declare Globally
@property (strong) AVPlayerViewController *playerVC;
@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];

    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200, 50)];
    button.center = self.view.center;
    button.backgroundColor = [UIColor blueColor];
    [button setTitle:@"Query Songs" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:button];

    UIButton *button2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200, 50)];
    button2.center = CGPointMake(button.center.x, button.center.y + 200);
    button2.backgroundColor = [UIColor blueColor];
    [button2 setTitle:@"Listen to the first song" forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(button2Clicked) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:button2];

}
-(void)button2Clicked{
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    NSURL *url = [NSURL URLWithString:[_requestedSong objectForKey:@"previewUrl"]];
    NSMutableURLRequest *req = [[NSMutableURLRequest alloc]initWithURL:url];
    NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:req];
    [task resume];
}

-(void)buttonClicked{

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/search?media=movie&entity=movie&term=Mad"];
    NSMutableURLRequest *req = [[NSMutableURLRequest alloc]initWithURL:url];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:req];
    [task resume];
}

-(NSURL*)localFilePathForURL:(NSURL *) previewUrl{
    //get the directory to use
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) objectAtIndex:0];
    //create the full path
    NSString *fullPath = [documentsPath stringByAppendingPathComponent:previewUrl.lastPathComponent];
    //append the filename and append to document path url
    return [NSURL fileURLWithPath:fullPath];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
    NSURL* originalURL = downloadTask.originalRequest.URL;
    NSURL *destination = [self localFilePathForURL:originalURL];
    NSLog(@"Destination: %@",destination);
    NSFileManager *defaultFileManager = [NSFileManager defaultManager];
    if([defaultFileManager fileExistsAtPath:destination.absoluteString]){
        [defaultFileManager removeItemAtURL:destination error:nil];
    }

    NSError *error;

    @try {
        [defaultFileManager copyItemAtURL:location toURL:destination error:&error];
    } @catch (NSException *exception) {
        NSLog(@"copy caught with exception: %@",exception);
        return;
    }


    dispatch_async(dispatch_get_main_queue(), ^{
        _player = [AVPlayer playerWithURL:destination];
        _playerVC = [AVPlayerViewController new];
        _playerVC.player = _player;
        [self presentViewController:_playerVC animated:YES completion:^{
            [_player play];
        }];

    });



    NSLog(@"Hello");
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data{
    NSError *error2;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:1 error:&error2];
    _requestedSong = [[dict valueForKey:@"results"] objectAtIndex:0];
    NSLog(@"Searched: %@",[_requestedSong objectForKey:@"trackName"]);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    completionHandler(NSURLSessionResponseAllow);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

.h file: .h文件:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>


@end

UPDATE: 更新:

Upon using the actual URL endpoint for mad max instead of downloading the video, it also displays a blank video. 将实际的URL端点用于mad max而不是下载视频后,它还会显示空白视频。 This must mean there's something weird about the format of the video or how it interacts with the AVPlayer. 这一定意味着视频的格式或其与AVPlayer的交互方式有些奇怪。

You should setup observer for AVPlayer status to call play only when it will be ready to play. 您应该为AVPlayer状态设置观察者,以仅在准备好播放时才调用播放。 How to do it - check answers here: AVPlayer And Local Files 怎么做-在这里检查答案: AVPlayer和本地文件

check the following 检查以下内容

if ((_playerVC.player.rate != 0) && (_playerVC.player.error == nil)) {
    // player is playing
} else {
   // Something wrong
}

also you can observe the rate property of the player. 您也可以观察播放器的rate属性。 More info here 更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM