OGeek|极客世界-中国程序员成长平台

标题: ios - 找出 Music.app 中正在播放的歌曲 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 23:49
标题: ios - 找出 Music.app 中正在播放的歌曲

在 iOS 上,我的应用程序是否可以找出音乐应用程序中当前正在播放的歌曲?例如,如果他们在使用我的应用程序时在后台播放歌曲,我可以获取有关该歌曲的信息吗?如果可以的话,有没有办法让我的应用程序在新歌开始播放时收到某种通知?谢谢!



Best Answer-推荐答案


有可能获得这样的一些信息还有许多其他 MPMediaItemProperties)就问题中的第二个问题而言,我认为当您的应用程序处于后台状态时这是不可能的。

编辑:也许您可以根据需要在后台每隔 xx 秒调用一次此代码,并比较这些值以查看音乐是否确实改变了您自己。请注意,尽管您的应用在后台运行的时间有限,但在此时间过后,您将无法获得更新后的值。

#import <MediaPlayer/MediaPlayer.h>

@property (nonatomic, strong) MPMediaItem *lastItem;

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:20.0 target:self selectorselector(checkIfSongChanged) userInfo:nil repeats:YES];
    [timer fire];
}

- (void)checkIfSongChanged
{
    if ([[MPMusicPlayerController iPodMusicPlayer] playbackState] == MPMusicPlaybackStatePlaying)
    {
        MPMediaItem *nowPlayingMediaItem =
        [[MPMusicPlayerController iPodMusicPlayer] nowPlayingItem];

        if (self.lastItem && nowPlayingMediaItem != self.lastItem)
        {
            NSLog(@"New media item is: %@",nowPlayingMediaItem);
        }

        self.lastItem = nowPlayingMediaItem;

        NSLog(@"Media item is: %@,",nowPlayingMediaItem);
    }
}

AppDelegate.m:

- (void)applicationDidEnterBackgroundUIApplication *)application
{
    UIBackgroundTaskIdentifier __block task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^
    {
        [[UIApplication sharedApplication] endBackgroundTask:task];
        task = UIBackgroundTaskInvalid;
    }];
}

关于ios - 找出 Music.app 中正在播放的歌曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24749339/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4