app中正在播放的歌曲

app中正在播放的歌曲

本文介绍了找出Music.app中正在播放的歌曲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On iOS, is there a way for my application to find out what song is currently playing in the Music application? For example, if they are playing a song in the background while using my app, can I get information on that song? And if I can, is there a way for my app to receive some sort of notification when a new song begins playing? Thanks!

推荐答案

可以得到一些信息:(还有很多其他MPMediaItemProperties)在问题内,我不相信是可能的,而你的应用程序处于后台状态。

It is possible to get some information as such: (There's many other MPMediaItemProperties too) As far as your 2nd question within the question, I do not believe that is possible while your app is in a background state.

编辑:您可以在后台每隔xx秒调用此代码,并比较这些值,看看音乐是否改变了自己。请注意,虽然您的应用程式可以在背景中执行有限的时间,但过了后,您将无法取得更新后的值。

perhaps you could call this code below every xx seconds in the background when you want, and compare the values to see if the music did change yourself. Please note though your app has a finite amount of time it can run in the background, after that has elapsed, you will not get the updated values.

#import <MediaPlayer/MediaPlayer.h>

@property (nonatomic, strong) MPMediaItem *lastItem;

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:20.0 target:self selector:@selector(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:

AppDelegate.m:

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

这篇关于找出Music.app中正在播放的歌曲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 04:26