【问题标题】:Using AVPlayer and AVPlayerViewController, but audio and video not present使用 AVPlayer 和 AVPlayerViewController,但音频和视频不存在
【发布时间】:2016-12-30 21:51:20
【问题描述】:

我的代码如下所示:

_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 文件,它正确地给了我音频。我还将目的地的 url 替换为一些远程 url,并且适用于视频。这让我相信它与我的视频有关。奇怪的是,我的 AVPlayerViewController 确实显示所有正常控件的黑屏,甚至显示视频为 2 分 23 秒。手动打开视频文件,我看到也是2分23秒。

我可以通过拖动指示视频位置的白点正确地向前浏览视频,但我什么也没听到,除了黑屏和控件我什么也看不到。

TL;DR

NSLog(@"目的地:%@",destination); 打印:file:///Users/MyLogin/Library/Developer/CoreSimulator/Devices/694F4C94-F785-4931-A312-4C3E7DE8673A/data/Containers/Data/Application/76C923BE-5B25-41F7-9145-63414657FDF6/Documents/mzvf_59140025198 .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 的交互方式有些奇怪。

【问题讨论】:

  • 你检查过控制台的输出吗?这可能是 IOS 中不那么新的应用程序传输安全性。您需要允许来自您的源的连接,因为默认情况下 ios 会阻止任何不是 https 的内容。
  • 我的控制台输出完全是我自己的。我已经允许任意加载,但这应该纯粹是下载相关的权利吗?我正在尝试查看本地视频文件。即便如此,我正在查看一个具有正确时间范围的空白屏幕作为我要查看的视频,所以我被允许访问该文件,所以我认为它不可能是这样的。
  • 哦,我明白了,你是如何加载你的资产的?您可能希望为您的 AVPlayer 使用备用构造函数,以便您可以从文件中传递资产。您可以使用(AVPlayerItem *)playerItemWithAsset:(AVAsset *)asset 实例化您的资产,然后使用(instancetype)initWithPlayerItem:(AVPlayerItem *)item 实例化您的AVPlayer。
  • 得到相同的行为 AVAsset *asset = [AVAsset assetWithURL:destination]; AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset]; _player = [AVPlayer playerWithPlayerItem:item]; _playerVC = [AVPlayerViewController 新]; _playerVC.player = _player;
  • 在问题中添加了 nsurl 打印

标签: ios objective-c video avplayer avplayerviewcontroller


【解决方案1】:

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

【讨论】:

  • 没用,我这样设置观察者:[_player addObserver:self forKeyPath:@"status" options:0 context:nil];观察者方法看起来像这样: if (object == _player && [keyPath isEqualToString:@"status"]) { if (_player.status == AVPlayerStatusReadyToPlay) { [_player play]; } else if (_player.status == AVPlayerStatusFailed) { // 出了点问题。 player.error 应该包含一些信息 } } 它被调用了,标志 AVPlayerStatusReadyToPlay 为真,屏幕仍然是空白的。
  • 我很确定这与视频格式或视频本身有关? a1238.phobos.apple.com/us/r1000/155/Video30/v4/12/18/48/…
  • 您是否尝试过其他文件,例如 720x400 或 640x360 等“易于播放”分辨率的 mp3 或 mp4?
【解决方案2】:

检查以下内容

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

您还可以观察播放器的速率属性。更多信息here

【讨论】:

  • [_player play]; if ((_playerVC.player.rate != 0) && (_playerVC.player.error == nil)) { NSLog(@"看起来它正在工作!"); } else { NSLog(@"出了点问题"); } 打印:看起来它正在工作!
  • 还是空白,没有音频,我认为它与视频有关:a1238.v2.phobos.apple.com.edgesuite.net/us/r1000/155/Video30/v4/… 当我点击它并在浏览器中查看时它是空白的,但是当我通过我的代码下载它时并打开我在 quicktime 上看到视频的文件。
  • 试一下其他视频是否可以播放
  • 我尝试了来自不同提供商的另一个视频,它成功了。但是,如果我在使用上面提供的下载功能后使用quicktime手动访问视频时可以播放视频,为什么我无法使用媒体播放器观看?
  • 这些视频有什么区别。也看看这里stackoverflow.com/questions/1535836/…
猜你喜欢
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多