我使用AVPlayer从网址播放歌曲,我初始化并在我的viewcontroller中分配它,现在我有一个问题,当我导航到另一个视图控制器并返回主播放器播放歌曲细节和滑块更新应保留但问题是当我再次导
解决方案2:
创建一个包含AVAudioPlayer实例的Singleton类.例如
MediaManager.h
@interface MediaManager : NSObject{ } +(MediaManager *)sharedInstance; -(void)playWithURL:(NSURL *)url; -(float)currentPlaybackTime; @end
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”等.
样本方法调用
[[MediaManager sharedInstance] playWithURL:url]; float currentTime = [[MediaManager sharedInstance] currentPlaybackTime]; // Update slider