gpt4 book ai didi

ios - 添加子层 AVPlayer 共享实例/管理器时出错

转载 作者:行者123 更新时间:2023-11-29 12:13:07 25 4
gpt4 key购买 nike

我收到一个错误

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 中将要呈现内容的播放器代码。

所以在你的 View Controller 中:

@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;

}

编辑 我从您的示例代码中注意到该 URL 指向一个 MP3。在这种情况下,您根本不需要担心创建 AVPlayerLayer 的问题。只需实例化播放器并调用 play 就足够了。

关于ios - 添加子层 AVPlayer 共享实例/管理器时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32769827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com