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

时间:2016-08-23 22:43:29

标签: ios objective-c video avplayer avplayerviewcontroller

我的代码如下所示:

_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代表AVPlayer,_playerVC代表AVPlayerViewController。我对这些对象有强烈的全局引用。

使用终端,我播放了位于目的地的文件(打开-a quicktime \ player destinationURLAbsoluteString)并看到文件正在播放时已正确加载。

这是一个m4v文件。我播放了一个m4a文件,它正确地给了我音频。我还将我的目的地网址替换为一些远程网址,这对于视频来说非常有用。这让我相信它与我的视频有关。有点奇怪的是,我的AVPlayerViewController确实显示了带有所有普通控件的黑屏,甚至还显示了2分23秒的视频。手动打开视频文件后,我可以看到它也是2分23秒。

我可以通过拖动指示视频位置的白点来正确转发视频,但我从来没有听到任何声音,除了黑屏和控件之外我什么都看不到。

TL; DR

NSLog(@“目的地:%@”,目的地); 打印: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

总而言之,看起来我正在正确地检索视频,但由于某种原因,我的播放器控制器完全是黑色的,没有音频。任何帮助深表感谢。

源代码:

.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文件:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>


@end

更新:

使用mad max的实际URL端点而不是下载视频时,它还会显示空白视频。这必然意味着视频的格式或它与AVPlayer的交互方式有些奇怪。

2 个答案:

答案 0 :(得分:0)

您应该将AVPlayer状态的观察者设置为仅在准备播放时才调用播放。 怎么做 - 在这里查看答案:AVPlayer And Local Files

答案 1 :(得分:0)

检查以下内容

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

你也可以观察玩家的费率属性。更多信息here