iPhoneでIpodの音楽再生の方法



久しぶりにソースの投稿。

新しいソフトの開発で、簡単なサンプルを作ってみました。

いつもの通り適当なサンプルなので脳内変換してみてください。(笑

どこかの時点で、まともな解説を入れたいですが・・・・


では本題です。iPhoneIpodの音楽再生の方法です。

1.「View-basedApplication」を「testMusic」で新規作成。


2.Frameworksは、「MediaPlayer.framework」が必要ですので追加してください。


3.ソースを修正。


testMusicViewController.h


#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>


@interface testMusicViewController : UIViewController {
MPMusicPlayerController *musicPlayer;
NSMutableArray *userCombinedMediaItems;
}

- (IBAction)myAction1:(id)sender;
- (IBAction)myAction2:(id)sender;
- (IBAction)myAction3:(id)sender;
- (IBAction)myAction4:(id)sender;

@property (nonatomic, retain) MPMusicPlayerController *musicPlayer;
@property (nonatomic, retain) NSMutableArray *userCombinedMediaItems;

@end

testMusicViewController.m


#import "testMusicViewController.h"

@implementation testMusicViewController

@synthesize musicPlayer;
@synthesize userCombinedMediaItems;

- (IBAction)myAction1:(id)sender {
MPMusicPlaybackState playbackState = [musicPlayer playbackState];

if (playbackState == MPMusicPlaybackStateStopped || playbackState == MPMusicPlaybackStatePaused) {
[musicPlayer play];
} else if (playbackState == MPMusicPlaybackStatePlaying) {
[musicPlayer pause];
}
}

- (IBAction)myAction2:(id)sender {
MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSArray *itemsFromGenericQuery = [everything items];
NSMutableArray *combinedMediaItems = [[[NSMutableArray alloc] initWithCapacity:1] autorelease];

[everything release];

for (MPMediaItem *song in itemsFromGenericQuery) {
NSString *persistentID = [NSString stringWithFormat:@"%@",[song valueForProperty: MPMediaItemPropertyPersistentID]];
if([persistentID isEqualToString:@"9532744532149860656"]) // PersistentIDを任意に変更してください
{
[combinedMediaItems addObject:song];
NSLog(@"見つかった!!");
}
if([persistentID isEqualToString:@"3329049609616439578"]) // PersistentIDを任意に変更してください
{
[combinedMediaItems addObject:song];
NSLog(@"見つかった!!");
}
if([persistentID isEqualToString:@"16952316297112017607"]) // PersistentIDを任意に変更してください
{
[combinedMediaItems addObject:song];
NSLog(@"見つかった!!");
}
}
[musicPlayer setQueueWithItemCollection: [MPMediaItemCollection collectionWithItems:combinedMediaItems]];
[musicPlayer play];

}

/* グループごとのデータ取得 */
- (IBAction)myAction3:(id)sender {
MPMediaQuery *query = [[MPMediaQuery alloc] init];

// メディアクエリのグルーピングタイプを設定
[query setGroupingType: MPMediaGroupingAlbum];
NSArray *albums = [query collections];

for (MPMediaItemCollection *album in albums) {
MPMediaItem *representativeItem = [album representativeItem];
NSString *artistName =
[representativeItem valueForProperty: MPMediaItemPropertyArtist];

NSString *albumName =
[representativeItem valueForProperty: MPMediaItemPropertyAlbumTitle];
NSLog(@"+++++++++++++++++++++++++++++");
NSLog (@"%@ by %@", albumName, artistName);

NSArray *songs = [album items];

NSLog(@"