---
title: "ios 获取音乐库音乐相关（转）"
author: "jguangyou"
date: "2012-11-22T15:07:28Z"
tags: []
categories: ["移动开发"]
slug: "ios"
draft: false
lastmod: "2012-11-22T15:09:18Z"
id: 1733312
url: "https://deep-fish.iteye.com/blog/1733312"
---

## 1.访问音乐库的两种方法，如下图

（只能访问音频文件，如music，podcast，audiobook等）

## []()2.MPMusicPlayerController的使用

有两种播放器可以选择，一种是application　music　player，另外一种是iPod　music　player。

第一种播放器是一种内部播放器，当程序对出后停止播放；而第二种播放器则与iPod播放器内的信息相关，退出之后不会停止播放。获取方式如下：

- + applicationMusicPlayer
- + iPodMusicPlayer

播放之前需要设置播放器的播放队列

- – setQueueWithQuery:
- – setQueueWithItemCollection:

管理播放模式和播放状态的一些属性

- currentPlaybackTime  property
- nowPlayingItem  property
- playbackState  property
- repeatMode  property
- shuffleMode  property
- volume  property

播放状态　MPMusicPlaybackState

enum {

   MPMusicPlaybackStateStopped,

   MPMusicPlaybackStatePlaying,

   MPMusicPlaybackStatePaused,

   MPMusicPlaybackStateInterrupted,

   MPMusicPlaybackStateSeekingForward,

   MPMusicPlaybackStateSeekingBackward

};

typedef NSInteger MPMusicPlaybackState;

播放控制方法

- – play
- – pause
- – stop
- – beginSeekingForward
- – beginSeekingBackward
- – endSeeking
- – skipToNextItem
- – skipToBeginning
- – skipToPreviousItem

播放状态发生变化时可以发送通知

- – beginGeneratingPlaybackNotifications
- – endGeneratingPlaybackNotifications

MPMusicPlayerControllerPlaybackStateDidChangeNotification

可以通过该通知来改变播放按钮的样式

MPMusicPlayerControllerNowPlayingItemDidChangeNotification

MPMusicPlayerControllerVolumeDidChangeNotification

具体步骤

１.注册和开始发送通知

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

01. Listing 2-1  Registering for and activating music player notifications
02. NSNotificationCenter \*notificationCenter = \[NSNotificationCenter defaultCenter];
03. [notificationCenter
04. addObserver: self
05. selector:    @selector (handle\_NowPlayingItemChanged:)
06. name:        MPMusicPlayerControllerNowPlayingItemDidChangeNotification
07. object:      musicPlayer];
08. [notificationCenter
09. addObserver: self
10. selector:    @selector (handle\_PlaybackStateChanged:)
11. name:        MPMusicPlayerControllerPlaybackStateDidChangeNotification
12. object:      musicPlayer];
13. \[musicPlayer beginGeneratingPlaybackNotifications];

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

01. Listing 2-2  Unregistering and deactivating music player notifications
02. \[\[NSNotificationCenter defaultCenter]
03. removeObserver: self
04. name:           MPMusicPlayerControllerNowPlayingItemDidChangeNotification
05. object:         musicPlayer];
06. \[\[NSNotificationCenter defaultCenter]
07. removeObserver: self
08. name:           MPMusicPlayerControllerPlaybackStateDidChangeNotification
09. object:         musicPlayer];
10. \[musicPlayer endGeneratingPlaybackNotifications];

２.创建并配置一个Music　Player

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

1. Listing 2-3  Creating an application music player
2. MPMusicPlayerController* appMusicPlayer =
3. \[MPMusicPlayerController applicationMusicPlayer];
4. \[appMusicPlayer setShuffleMode: MPMusicShuffleModeOff];
5. \[appMusicPlayer setRepeatMode: MPMusicRepeatModeNone];

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

1. Listing 2-4  Creating an iPod music player
2. MPMusicPlayerController* iPodMusicPlayer =
3. \[MPMusicPlayerController iPodMusicPlayer];
4. if (\[iPodMusicPlayer nowPlayingItem]) {
5. // Update the UI (artwork, song name, volume indicator, etc.)
6. //        to reflect the iPod state
7. }

３.设置播放队列

- – setQueueWithQuery:
- – setQueueWithItemCollection:

４.控制播放

## []()3.MPMediaPickerController的使用

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

01. &lt;span style="font-size:18px;"&gt;- (IBAction)addSongsToMusicPlayer:(id)sender
02. {
03. MPMediaPickerController \*mpController = \[\[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
04. mpController.delegate = self;
05. mpController.prompt = @"Add songs to play";
06. mpController.allowsPickingMultipleItems = YES;
07. \[self presentModalViewController:mpController animated:YES];
08. \[mpController release];
09. }
10. &lt;/span&gt;

主要是设置代理和选择多媒体类型，然后通过代理方法来获取选中的歌曲

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

01. &lt;span style="font-size:18px;"&gt;#pragma mark - Media Picker Delegate Methods
02. - (void)mediaPicker:(MPMediaPickerController \*)mediaPicker didPickMediaItems:(MPMediaItemCollection \*)mediaItemCollection
03. {
04. \[self.musicPlayer setQueueWithItemCollection:mediaItemCollection];
05. \[self dismissModalViewControllerAnimated:YES];
06. }
07. - (void)mediaPickerDidCancel:(MPMediaPickerController \*)mediaPicker
08. {
09. \[self dismissModalViewControllerAnimated:YES];
10. }&lt;/span&gt;

## []()4.MPMediaItem

用此方法来获取item的metadata

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

1. - (id) valueForProperty: (NSString \*) property

NSString \*const MPMediaItemPropertyTitle;                   

NSString \*const MPMediaItemPropertyAlbumTitle;              

NSString \*const MPMediaItemPropertyArtist;                 

## []()5.MPMediaItemCollection

collection是一组有序的item集合，可用同样的方法来获取collection的metadata

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

1. - (id) valueForProperty: (NSString \*) property

创建

- + collectionWithItems:
- – initWithItems:

属性

- items  property
- representativeItem  property
- count  property
- mediaTypes  property

## []()6.MPMediaPlaylist

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

01. MPMediaQuery \*myPlaylistsQuery = \[MPMediaQuery playlistsQuery];
02. NSArray \*playlists = \[myPlaylistsQuery collections];
03. for (MPMediaPlaylist \*playlist in playlists) {
04. NSLog (@"%@", \[playlist valueForProperty: MPMediaPlaylistPropertyName]);
05. NSArray \*songs = \[playlist items];
06. for (MPMediaItem \*song in songs) {
07. NSString \*songTitle =
08. \[song valueForProperty: MPMediaItemPropertyTitle];
09. NSLog (@"\\t\\t%@", songTitle);
10. }
11. }

## []()7.MPMediaQuery

需要设置两个属性: filter  and  grouping type

filter描述查询内容，grouping type 描述返回内容的排列方式

查询可以获取items，也可以获取collections

- When you ask for items, the query returns a collection containing all the items that match the filter. The items are in “natural” order, meaning that they are ordered as iTunes shows them on the desktop.
- When you ask for collections, the media query employs not only its filter but also its grouping type.

![](http://blog.csdn.net/nerohoop/article/details/7211246)

获取全部歌曲

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

1. MPMediaQuery \*everything = \[\[MPMediaQuery alloc] init];
2. NSLog(@"Logging items from a generic query...");
3. NSArray \*itemsFromGenericQuery = \[everything items];
4. for (MPMediaItem \*song in itemsFromGenericQuery) {
5. NSString \*songTitle = \[song valueForProperty: MPMediaItemPropertyTitle];
6. NSLog (@"%@", songTitle);
7. }

获取名为“Happy the Clown”的艺术家的歌曲

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

1. MPMediaPropertyPredicate \*artistNamePredicate =
2. [MPMediaPropertyPredicate predicateWithValue: @"Happy the Clown"
3. forProperty: MPMediaItemPropertyArtist];
4. MPMediaQuery \*myArtistQuery = \[\[MPMediaQuery alloc] init];
5. \[myArtistQuery addFilterPredicate: artistNamePredicate];
6. NSArray \*itemsFromArtistQuery = \[myArtistQuery items];

多个查找条件，查找名为"Sad the Joker"的艺术家的"Stair Tumbling"专辑

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

1. MPMediaPropertyPredicate \*artistNamePredicate =
2. [MPMediaPropertyPredicate predicateWithValue: @"Sad the Joker"
3. forProperty: MPMediaItemPropertyArtist];
4. MPMediaPropertyPredicate \*albumNamePredicate =
5. [MPMediaPropertyPredicate predicateWithValue: @"Stair Tumbling"
6. forProperty: MPMediaItemPropertyAlbumTitle];
7. MPMediaQuery \*myComplexQuery = \[\[MPMediaQuery alloc] init];
8. \[myComplexQuery addFilterPredicate: artistNamePredicate];
9. \[myComplexQuery addFilterPredicate: albumNamePredicate];

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

1. Listing 4-4  Applying multiple predicates when initializing a media query
2. NSSet \*predicates =
3. \[NSSet setWithObjects: artistNamePredicate, albumNamePredicate, nil];
4. MPMediaQuery \*specificQuery =
5. \[\[MPMediaQuery alloc] initWithFilterPredicates: predicates];

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

1. Listing 4-5  Testing if a property key can be used for a media property predicate
2. if (\[MPMediaItem canFilterByProperty: MPMediaItemPropertyGenre]) {
3. MPMediaPropertyPredicate \*rockPredicate =
4. [MPMediaPropertyPredicate predicateWithValue: @"Rock"
5. forProperty: MPMediaItemPropertyGenre];
6. \[query addFilterPredicate: rockPredicate];
7. }

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

01. Listing 4-6  Using grouping type to specify media item collections
02. MPMediaQuery \*query = \[\[MPMediaQuery alloc] init];
03. [query addFilterPredicate: [MPMediaPropertyPredicate
04. predicateWithValue: @"Moribund the Squirrel"
05. forProperty: MPMediaItemPropertyArtist]];
06. // Sets the grouping type for the media query
07. \[query setGroupingType: MPMediaGroupingAlbum];
08. NSArray \*albums = \[query collections];
09. for (MPMediaItemCollection \*album in albums) {
10. MPMediaItem \*representativeItem = \[album representativeItem];
11. NSString \*artistName =
12. \[representativeItem valueForProperty: MPMediaItemPropertyArtist];
13. NSString \*albumName =
14. \[representativeItem valueForProperty: MPMediaItemPropertyAlbumTitle];
15. NSLog (@"%@ by %@", albumName, artistName);
16. NSArray \*songs = \[album items];
17. for (MPMediaItem \*song in songs) {
18. NSString \*songTitle =
19. \[song valueForProperty: MPMediaItemPropertyTitle];
20. NSLog (@"\\t\\t%@", songTitle);
21. }
22. }

query的一些简便构造方法

![](http://hi.csdn.net/attachment/201201/21/0_13271234938CL8.gif)

专辑封面的使用

**\[plain]** [view plain](http://blog.csdn.net/nerohoop/article/details/7211246 "view plain")[copy](http://blog.csdn.net/nerohoop/article/details/7211246 "copy")[print](http://blog.csdn.net/nerohoop/article/details/7211246 "print")[?](http://blog.csdn.net/nerohoop/article/details/7211246 "?")

01. Listing 4-7  Displaying album artwork for a media item
02. MPMediaItemArtwork \*artwork =
03. \[mediaItem valueForProperty: MPMediaItemPropertyArtwork];
04. UIImage \*artworkImage =
05. \[artwork imageWithSize: albumImageView.bounds.size];
06. if (artworkImage) {
07. albumImageView.image = artworkImage;
08. } else {
09. albumImageView.image = \[UIImage imageNamed: @"noArtwork.png"];
10. }