MacOS X

【Objective-C】バックグラウンドで音楽再生 【Background play music】

ネットを見てもあまりなかったので。
メモとして。


[ AppDelegate.m ]
--------------------------------------------
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    //AudioSesstion create
    AVAudioSession* session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
  
    return YES;
}

--------------------------------------------



[ MusicPlayViewController.h ]
--------------------------------------------
//
//  MusicPlayViewController.h
//  SocialMuscle
//
//  Created by hoehoe on 2012/09/05.
//  Copyright (c) 2012年 hoehoe. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import "GlobalObjects.h"
#import <AVFoundation/AVFoundation.h>

@interface MusicPlayViewController : UIViewController<MPMediaPickerControllerDelegate>
{

}

@property(nonatomic, retain)MPMediaPickerController* picker;
@property (weak, nonatomic) IBOutlet UILabel *lbl_musicArtist;
@property (weak, nonatomic) IBOutlet UILabel *lbl_musicTitle;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *btn_musicPlay;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *btn_musicPause;

- (IBAction)btn_playlistPush:(id)sender;
- (IBAction)btn_closePush:(id)sender;
- (IBAction)btn_musicPlayPush:(id)sender;
- (IBAction)btn_musicSkipNext:(id)sender;
- (IBAction)btn_musicSkipPrev:(id)sender;
- (IBAction)btn_musicPausePush:(id)sender;

@end
--------------------------------------------

[ MusicPlayViewController.m ]
--------------------------------------------
//
//  MusicPlayViewController.m
//  SocialMuscle
//
//  Created by hoehoe on 2012/09/05.
//  Copyright (c) 2012年 hoehoe. All rights reserved.
//

#import "MusicPlayViewController.h"

@interface MusicPlayViewController ()

@end

@implementation MusicPlayViewController

@synthesize picker;
@synthesize lbl_musicArtist;
@synthesize lbl_musicTitle;
@synthesize btn_musicPlay;
@synthesize btn_musicPause;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    picker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeAnyAudio];
    picker.delegate = self;
   
    [picker setAllowsPickingMultipleItems: YES];
    NSString* promptTitle = NSLocalizedString(@"MUSIC_PROMPT", nil);
    //picker.prompt = @"曲を追加して下さい。";
    picker.prompt = promptTitle;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if(musicCollection != nil){
        [self setMusicProperty];
    }
   
    if(playing == YES){
        [btn_musicPlay setEnabled:NO];
        [btn_musicPause setEnabled:YES];
    }else{
        [btn_musicPlay setEnabled:YES];
        [btn_musicPause setEnabled:NO];
    }
}

- (void)viewDidUnload
{
    [self setBtn_musicPlay:nil];
    [self setBtn_musicPause:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - MPMediaPickerController delegate

- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) collection
{
    if([collection count] > 0){
        // Set global valiables parameter
        collectionCount = [collection count];
        musicCollection = collection;

        if(musicItems == nil){
            musicItems = [musicCollection items];
        }
       
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker {
   
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)btn_playlistPush:(id)sender {
    [self presentViewController:picker animated:YES completion:nil];
}

- (IBAction)btn_closePush:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)btn_musicPlayPush:(id)sender {
    if(collectionCount > 0){
        //再生中
        if(playing == YES){
            [btn_musicPlay setEnabled:NO];
            [btn_musicPause setEnabled:YES];
        }else{
            [btn_musicPlay setEnabled:YES];
            [btn_musicPause setEnabled:NO];

            [self doPlayMusic];
           
            [btn_musicPlay setEnabled:NO];
            [btn_musicPause setEnabled:YES];
            [self setMusicProperty];
        }
    }
}

-(void)doPlayMusic{

    playing = YES;
    MPMediaItem* item = [musicItems objectAtIndex:selectedMusicCursor];
    NSURL* url = [item valueForProperty:MPMediaItemPropertyAssetURL];
    avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [avAudioPlayer play];
}

- (IBAction)btn_musicSkipNext:(id)sender {
    [avAudioPlayer pause];
   
    if(selectedMusicCursor < (collectionCount - 1)){
        selectedMusicCursor++;
    }
    //NSLog(@"cursor: %d", selectedMusicCursor);
    [self doPlayMusic];
    [self setMusicProperty];

}

- (IBAction)btn_musicSkipPrev:(id)sender {
    [avAudioPlayer pause];
   
    if(selectedMusicCursor > 0){
        selectedMusicCursor--;
    }
    //NSLog(@"cursor: %d", selectedMusicCursor);
    [self doPlayMusic];
    [self setMusicProperty];
}

- (IBAction)btn_musicPausePush:(id)sender {
    if(collectionCount > 0){
        //再生中
        if(playing == YES){
            [btn_musicPlay setEnabled:NO];
            [btn_musicPause setEnabled:YES];
           
            [avAudioPlayer pause];
            playing = NO;
           
            [btn_musicPlay setEnabled:YES];
            [btn_musicPause setEnabled:NO];
        }else{
            [btn_musicPlay setEnabled:YES];
            [btn_musicPause setEnabled:NO];
        }
    }
}

-(void) setMusicProperty
{
    //曲リスト
    //タイトルとアーティスト名表示 musicTitleとmusicArtistはラベル。
    MPMediaItem* mediaItem = [musicItems objectAtIndex:selectedMusicCursor];
   
    self.lbl_musicTitle.text = [mediaItem valueForProperty:MPMediaItemPropertyTitle];
    self.lbl_musicArtist.text = [mediaItem valueForProperty:MPMediaItemPropertyArtist];
}

@end
--------------------------------------------

[ GlobalObjects.h ]
--------------------------------------------
//
//  GlobalObjects.h
//  SocialMuscle
//
//  Created by hoehoe on 2012/09/07.
//  Copyright (c) 2012年 hoehoe. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import "MyAccount.h"

NSManagedObjectContext* managedObjectContextGlobal;

//BOOL callSettingViewGlobal;

NSString* intervalStringGlobal;
NSDate* recordDateGlobal;


/*  MusicPlayer Global valiables */
MPMediaItemCollection * musicCollection;
//MPMediaQuery* query;
AVAudioPlayer* avAudioPlayer;
int collectionCount;
int selectedMusicCursor;
NSArray* musicItems;
BOOL playing;

@interface GlobalObjects : NSObject

@end
--------------------------------------------


こんな感じで。


このページの先頭へ