我收到错误
没有可见的@interfcae GlobalMediaPlayer声明了选择器添加子层
·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];
答案 0 :(得分:1)
将AVPlayer
代码包装在一个单例中并没有什么好处,因为播放器需要能够在CALayer
中呈现其视频,因此通常最好将播放器代码放在{{1}中1}}即将展示内容。
所以在你的视图控制器中:
UIViewController
修改我从示例代码中注意到,该网址指向MP3。在这种情况下,您根本不必担心创建@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;
}
。只需实例化播放器并调用AVPlayerLayer
即可。