以下是我的两种观点的布局:
基本上我的目标是让VC2
每次都开始'新鲜',包括一个MPMusicPlayerController
。我的印象是unwindsegue
删除了新视图的实例以及它的资源,但音乐播放器没有停止。
在VC2
结束之前,它会运行一个功能,取消注册所有媒体播放器通知并设置音乐播放器本身= nil。但是当我返回VC1
时我仍然可以听到播放的音乐,当我创建VC2
的新实例时,我的'新'音乐播放器控制器不起作用(没有注册通知)。
一些代码:
音乐播放器已实例化(VC2
):
- (void)viewDidLoad
{
[super viewDidLoad];
musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
[self registerMediaPlayerNotifications];
}
注册通知:
- (void) registerMediaPlayerNotifications
{
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver: self
selector: @selector (handle_NowPlayingItemChanged:)
name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object: musicPlayer];
[notificationCenter addObserver: self
selector: @selector (handle_PlaybackStateChanged:)
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
object: musicPlayer];
[notificationCenter addObserver: self
selector: @selector (handle_VolumeChanged:)
name: MPMusicPlayerControllerVolumeDidChangeNotification
object: musicPlayer];
[musicPlayer beginGeneratingPlaybackNotifications];
}
来自getNextSong
MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:test forProperty:MPMediaEntityPropertyPersistentID];
MPMediaQuery *query = [[MPMediaQuery alloc] init];
[query addFilterPredicate: predicate];
NSArray *queryResults = [query items];
for (MPMediaItem *song in queryResults) {
[musicPlayer setQueueWithQuery:query];
[musicPlayer play];
}
在VC2
'展开'之前执行的代码:
- (IBAction)reset:(id)sender {
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object: musicPlayer];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
object: musicPlayer];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerVolumeDidChangeNotification
object: musicPlayer];
[musicPlayer endGeneratingPlaybackNotifications];
[musicPlayer stops];
musicPlayer = nil;
[self performSegueWithIdentifier:@"resetRoom" sender:self];
}
即使我将其设置为nil
,音乐也会继续播放,这告诉我它实际上并未被销毁。
编辑:更具体地说,我第二次实例化VC2
的新副本时,以下if
语句未执行:
- (void) handle_PlaybackStateChanged: (id) notification
{
MPMusicPlaybackState playbackState = [musicPlayer playbackState];
if(playbackState == MPMusicPlaybackStateStopped)
[self getNextSong];
[self playbackButton];
}
我已经通过调试器验证了playbackState
是0
我实例化的两次。但是第二次,if
语句永远不会发生。