添加子层 AVPlayer Shared 时出错 Instance/Manager

Error adding sublayer AVPlayer Shared Instance/Manager

我收到一个错误

No visible @interfcae GlobalMediaPlayer declares selector add sublayer

.h

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

    @interface GlobalMediaPlayer : NSObject
    +(GlobalMediaPlayer *)sharedInstance;
    -(void)playFromURL:(NSString *)url;

.m

#import "GlobalMediaPlayer.h"


static GlobalMediaPlayer *sharedInstance = nil;

@interface GlobalMediaPlayer ()

{
    AVPlayer *avPlayer;
}

@end

@implementation GlobalMediaPlayer

-(id)init{
    if(self = [super init]){

    }
    return self;
}


+(GlobalMediaPlayer *)sharedInstance{

    if(!sharedInstance){
        sharedInstance = [[[self class] alloc] init];
    }
    return sharedInstance;
}

-(void)playFromURL:(NSString *)url{

    avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:@"http://www.someurl/something.mp3"]];


    AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
    avPlayerLayer.frame = CGRectMake(0, 0, 1920, 1020);
    //[self addSublayer:avPlayerLayer]; <---- No visible @interfcae GlobalMediaPlayer declares selector add sublayer error

    [avPlayer play];

}

使用它

[[GlobalMediaPlayer sharedInstance] playFromURL:resourceUrl];

AVPlayer 代码包装在单例中没有真正的优势,因为播放器需要能够在 CALayer 中呈现其视频,因此通常最好将播放器代码放在UIViewController 将要呈现内容。

所以在你的视图控制器中:

@interface MyViewController: UIViewController

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, weak) AVPlayerLayer *playerLayer;

@end

- (void)playFromURL:(NSString *)url {

    //Instantiate the player and player layer
    AVPlayer *player = [AVPlayer playerWithURL:url];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];

    //Add the player layer as a sublayer of the desired view or subview
    playerLayer.frame = self.view.frame;
    [self.view.layer addSublayer:playerLayer];

    [player play];

    //Retain a reference to the player and player layer for controls/removal
    self.avPlayer = player;
    self.playerLayer = playerLayer;

}

Edit 我从您的示例代码中注意到 URL 指向 MP3。在那种情况下,您根本不需要担心创建 AVPlayerLayer 。简单地实例化播放器并调用 play 就足够了。