问题
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!
回答1:
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.
Edit: 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:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIBackgroundTaskIdentifier __block task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^
{
[[UIApplication sharedApplication] endBackgroundTask:task];
task = UIBackgroundTaskInvalid;
}];
}
来源:https://stackoverflow.com/questions/24749339/finding-out-what-song-is-playing-in-music-app