如何创建AVPlayer单例类 [英] How to create AVPlayer singleton class

查看:493
本文介绍了如何创建AVPlayer单例类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 AVPlayer 从网址播放歌曲,我初始化并在我的viewcontroller中分配它,现在我遇到了问题,当我导航到另一个视图控制器并返回到播放歌曲细节和滑块更新的主要播放器应该保留,但问题是当我再次导航到主播放器播放细节和滑块更新未发生但歌曲不断播放时。我怎么能避免这种情况,任何人都能告诉我一些例子。我需要创建一个单例类吗?如果是这样,如何为 AVPlayer创建单例类

Im using AVPlayer to play songs from urls, I initialized and allocate it in my viewcontroller, now I have a problem,when I navigate to another view controller and back to the main player playing song details and slider update should be remain but the problem is when I navigate to the main player again playing details and slider update not happening but song is continuously playing. How I can avoid this and can anyone show me some example. Do I need to create a singleton class? If so how to create a singleton class for the AVPlayer?

推荐答案

解决方案1:您还应该在PlayerViewController的viewWillAppear中更新UI。 Song继续播放,因为您不会退出或取消分配您的PlayerViewController。如果您弹出或关闭PlayerViewController,则此解决方案将无效。

Solution 1: You should update the UI also in viewWillAppear of your PlayerViewController. Song continues to play because you are not going back from or deallocating your PlayerViewController. If you pop or dismiss PlayerViewController , then this solution will not work.

解决方案2:
创建具有AVAudioPlayer实例的Singleton类在里面。例如

Solution 2: Create A Singleton class having AVAudioPlayer instance in it. e.g

MediaManager.h

MediaManager.h

@interface MediaManager : NSObject{

}

+(MediaManager *)sharedInstance;
-(void)playWithURL:(NSURL *)url;
-(float)currentPlaybackTime; 
@end

MediaManager.m

MediaManager.m

static MediaManager *sharedInstance = nil;
@interface MediaManager (){
AVAudioPlayer *audioPlayer;
}

@end
@implementation MediaManager

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

}
return self;
}

+(MediaManager *)sharedInstance{ 
 //create an instance if not already else return
    if(!sharedInstance){   
      sharedInstance = [[[self class] alloc] init];
    }
  return sharedInstance;
}

-(void)playWithURL:(NSURL *)url{
NSError *error = nil;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if(error == nil){
    [audioPlayer play];
}
}

-(float)currentPlaybackTime{

   return audioPlayer.currentTime;
}

@end

在其中添加其他必要的方法比如stopPlayer等。

Add other necessary methods in it like "stopPlayer" etc.

示例方法调用

[[MediaManager sharedInstance] playWithURL:url];
float currentTime = [[MediaManager sharedInstance] currentPlaybackTime];
// Update slider

这篇关于如何创建AVPlayer单例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆