gpt4 book ai didi

ios - 检测原生iOS Music App中当前正在播放的歌曲信息

转载 作者:行者123 更新时间:2023-12-01 18:58:57 25 4
gpt4 key购买 nike

我在本地 iOS 音乐应用程序中获取当前正在播放的歌曲信息(如(标题、艺术家...))时遇到了一些问题。

这是确切的问题,我的应用程序正在使用 MPMusicPlayerControlleriPodMusicPlayer这个属性是调用 myPlayer .当用户在我的应用程序中控制音乐时,我能够以这种方式显示当前的歌曲播放信息......

- (void)getTrackDescription {

// getting whats currently playing
self.nowPlayingItem = [myPlayer nowPlayingItem];

// song title currently playing
self.title = [self.nowPlayingItem valueForProperty:MPMediaItemPropertyTitle];

// if title is not fund Unknown will be displayed
if (title == (id)[NSNull null] || title.length == 0) {
title = @"Unknown";
}

// artist currently playing
self.artist = [self.nowPlayingItem valueForProperty:MPMediaItemPropertyArtist];

// if artist is not fund Unknown will be displayed
if (artist == (id)[NSNull null] || artist.length == 0) {
artist = @"Unknown";
}

//[self.currentlyPlaying setLineBreakMode:NSLineBreakByWordWrapping];

// displaying current artist and title song playing
[self.currentlyPlaying setText:[NSString stringWithFormat:@"%@ - %@", artist, title]];
}

但是,当用户将应用程序留在后台或仅使用 时,就会出现问题。控制中心更改歌曲.. 如果用户继续使用控制中心或音乐应用程序本身,我的应用程序仍会显示以前的歌曲信息并且没有任何更新。

我试图以这种方式解决问题......
- (void)viewDidLoad {
[super viewDidLoad];

if (self.myPlayer.playbackState == MPMusicPlaybackStatePlaying || self.myPlayer.playbackState == MPMusicPlaybackStateSeekingForward || self.myPlayer.playbackState == MPMusicPlaybackStateSeekingBackward){
// updating track name regardless the user uses app controllers or not
[self getTrackDescription];
}
}

我什至尝试评论 if 条件以查看我是否以这种方式获取歌曲信息,但这是同样的问题。

好吧,我希望有人可以帮助我并解释我做错了什么..

提前致谢...!

更新

这就是我目前所拥有的...我的 getTrackDescription 逻辑是相同的,但签名更改为 - (void)getTrackDescription:(id)notification
- (void)viewWillAppear:(BOOL)animated{

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

[notificationCenter addObserver:self
selector:@selector(getTrackDescription:)
name:MPMusicPlayerControllerPlaybackStateDidChangeNotification
object:self.myPlayer];
[self.myPlayer beginGeneratingPlaybackNotifications];

}

-(void)viewWillDisappear:(BOOL)animated{

[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMusicPlayerControllerPlaybackStateDidChangeNotification
object:self.myPlayer];
[self.myPlayer endGeneratingPlaybackNotifications];
}

最佳答案

您要做的是将您的 View Controller 作为观察者添加到 MPMusicPlayerControllerNowPlayingItemDidChangeNotification每次音乐播放器中的轨道更改时都会调用通知,这听起来很重要。不要忘记使用以下方法指定播放器何时开始/结束生成这些通知。

[[MPMusicPlayerController iPodMusicPlayer] beginGeneratingPlaybackNotifications];
[[MPMusicPlayerController iPodMusicPlayer] endGeneratingPlaybackNotifications];

关于ios - 检测原生iOS Music App中当前正在播放的歌曲信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24253264/

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