以下是我的两种观点的布局方式:
从本质上讲,我的目标是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
声明从未发生。