35
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iPhoneで再生中の曲情報を取得する方法

Posted at

MPMusicPlayerControllerを使ってiPhoneで再生中の曲情報を取得する方法です。

ヘッダ/プロパティ追加
#import <MediaPlayer/MediaPlayer.h>
// + MediaPlayer.frameworkをリンクライブラリに追加

@interface HogeVC ()

@property(nonatomic, strong) MPMusicPlayerController *player;

@end

iPodMusicPlayerはアプリ独自ではなくOS共通のプレイヤーを返します。なのでiPhone標準のMusicアプリで曲を再生した状態で、実装したアプリを起動するとMusicアプリの曲がそのまま取得できます。

前処理
-(void) viewDidLoad {
	[super viewDidLoad];

	self.player = [MPMusicPlayerController iPodMusicPlayer];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNowPlayingItemChanged:)
												 name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
											   object:self.player];

	[self.player beginGeneratingPlaybackNotifications];
}
後処理
-(void) viewDidUnload {
	[super viewDidUnload];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[self.player endGeneratingPlaybackNotifications];
}

MPMusicPlayerControllerNowPlayingItemDidChangeNotificationで曲が変わったことを検知できます。
最新の曲情報はMPMusicPlayerController.nowPlayingItemにアクセスして取得します。

曲変更時
-(void) onNowPlayingItemChanged:(NSNotification*)ntf {
	MPMediaItem *mediaItem = [self.player nowPlayingItem];
	NSInteger mediaType = [[mediaItem valueForProperty:MPMediaItemPropertyMediaType] integerValue];
	if (mediaType == MPMediaTypeMusic) {
		// 曲名
		_title = [mediaItem valueForProperty:MPMediaItemPropertyTitle];
		// アルバム名
		_albumTitle = [mediaItem valueForProperty:MPMediaItemPropertyAlbumTitle];
		// アーティスト名
		_artistName = [mediaItem valueForProperty:MPMediaItemPropertyArtist];
		
		// アートワーク(ジャケット写真)
		MPMediaItemArtwork *artwork = [mediaItem valueForProperty:MPMediaItemPropertyArtwork];
		_artworkImage = [artwork imageWithSize:CGSizeMake(80.0, 80.0)];
		
		// 再生時間		
		_duration = [[mediaItem valueForProperty:MPMediaItemPropertyPlaybackDuration] floatValue];
	}
}
35
35
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?