12.0~12.8 Audio and Videl 音频和视频

12.0. Introduction(Audio and Video)

AVFoundation.framework  使你能够播放或录制视频音频文件

MediaPlayer.framework 使你能够播放视频音频文件

在练习本章的习题时,别忘了把这两个framework引到你的工程里面,并记得引入头文件

#import <AVFoundation/AVFoundation.h>

#import <MediaPlayer/MediaPlayer.h>



12.1. Playing Audio Files

播放音频文件


#import "ViewController.h"

#import <AVFoundation/AVFoundation.h>


@interface ViewController ()<AVAudioPlayerDelegate>


@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

- (IBAction)buttonAction:(id)sender;


@end


@implementation ViewController


- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

  

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}




- (IBAction)buttonAction:(id)sender {

    [self testPlayMP3];

}


-(void)testPlayMP3

{

    dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(dispatchQueue, ^(void) {

        NSBundle *mainBundle = [NSBundle mainBundle];

        NSString *filePath = [mainBundle pathForResource:@"MySong"

                                                  ofType:@"mp3"];

        NSData   *fileData = [NSData dataWithContentsOfFile:filePath];

        NSError  *error = nil;

        /* Start the audio player */

        self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData

                                                         error:&error];

        /* Did we get an instance of AVAudioPlayer? */

        if (self.audioPlayer != nil){

            /* Set the delegate and start playing */

            self.audioPlayer.delegate = self;

            if ([self.audioPlayer prepareToPlay] &&

                [self.audioPlayer play]){

                /* Successfully started playing */

                NSLog(@"Successfully started playing");

            } else {

                /* Failed to play */

                NSLog(@"Failed to play");

            }

        } else {

            /* Failed to instantiate AVAudioPlayer */

            NSLog(@"Failed to instantiate AVAudioPlayer ");

        }

    });

}


- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{

    NSLog(@"Finished playing the song");

    /* The [flag] parameter tells us if the playback was successfully

     finished or not */

    if ([player isEqual:self.audioPlayer]){

        self.audioPlayer = nil;

    } else {

        /* Which audio player is this? We certainly didn't allocate

         this instance! */

        

    }

}


打印:

2014-06-27 14:26:33.012 cookbook7_12[218:1113] Successfully started playing


MP3文件别忘了添加,名字改为MySong.mp3


12.2. Handling Interruptions While Playing Audio

播放音乐时被打断的处理,比如来电话了。

home键入后台不触发


在前一节的代码中加入以下代码


//incoming call


-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player

{
   
/* Audio Session is interrupted. The player will be paused here */

    NSLog(@"%s",__FUNCTION__);

}


//end call


- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags{

    NSLog(@"%s",__FUNCTION__);

    if (flags == AVAudioSessionInterruptionOptionShouldResume && player != nil){

        [player play];

    }

}


打印:

2014-06-27 14:50:42.287 cookbook7_12[287:1103] Successfully started playing

2014-06-27 14:51:41.292 cookbook7_12[287:907] -[ViewController audioPlayerBeginInterruption:]

2014-06-27 14:51:42.733 cookbook7_12[287:907] -[ViewController audioPlayerEndInterruption:withOptions:]


12.3. Recording Audio

录制音频


#import "TestRecorderViewController.h"

#import <AVFoundation/AVFoundation.h>


@interface TestRecorderViewController ()<AVAudioPlayerDelegate, AVAudioRecorderDelegate>


@property (nonatomic, strong) AVAudioRecorder *audioRecorder;

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;


- (IBAction)buttonAction:(id)sender;


@end


@implementation TestRecorderViewController


- (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.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (IBAction)buttonAction:(id)sender {

    [self testReocrder];

}


-(void)testReocrder

{

    AVAudioSession *session = [AVAudioSession sharedInstance];

    [session setCategory:AVAudioSessionCategoryPlayAndRecord

             withOptions:AVAudioSessionCategoryOptionDuckOthers

                   error:nil];

    

    // ios7才有,低于ios7的会 unrecognized selector

/*    [session requestRecordPermission:^(BOOL granted) {

        if (granted) {

            [self startRecordingAudio];

        }else{

            NSLog(@"We don't have permission to record audio.");

            

        }

    }];

 */

    

    //书上的,sdk找不到这个方法

/*    if ([session requestRecordPermission]){

        [self startRecordingAudio];

    } else {

        NSLog(@"We don't have permission to record audio.");

    }

 */

    

    //所以我就干脆直接这样子了,结果还是可以录制的

    [self startRecordingAudio];


}


- (void) startRecordingAudio{

    NSError *error = nil;

    NSURL *audioRecordingURL = [self audioRecordingPath];

    self.audioRecorder = [[AVAudioRecorder alloc]

                          initWithURL:audioRecordingURL

                          settings:[self audioRecordingSettings]

                          error:&error];

    if (self.audioRecorder != nil){

        self.audioRecorder.delegate = self;

        /* Prepare the recorder and then start the recording */

        if ([self.audioRecorder prepareToRecord] && [self.audioRecorder record]){

            NSLog(@"Successfully started to record.");

            /* After 5 seconds, let's stop the recording process */

            [self performSelector:@selector(stopRecordingOnAudioRecorder:) withObject:self.audioRecorder

                       afterDelay:5.0f];

        } else {

            NSLog(@"Failed to record.");

            self.audioRecorder = nil;

        }

    } else {

        NSLog(@"Failed to create an instance of the audio recorder.");

    }

}


- (NSURL *) audioRecordingPath{

    NSFileManager *fileManager = [[NSFileManager alloc] init];

    NSURL *documentsFolderUrl =

    [fileManager URLForDirectory:NSDocumentDirectory

                        inDomain:NSUserDomainMask

               appropriateForURL:nil

                          create:NO

                           error:nil];

    return [documentsFolderUrl URLByAppendingPathComponent:@"Recording.m4a"];

}


- (NSDictionary *) audioRecordingSettings{

    /* Let's prepare the audio recorder options in the dictionary.

     Later we will use this dictionary to instantiate an audio

     recorder of type AVAudioRecorder */

    return @{AVFormatIDKey : @(kAudioFormatAppleLossless),

             AVSampleRateKey : @(44100.0f),

             AVNumberOfChannelsKey : @1,

             AVEncoderAudioQualityKey : @(AVAudioQualityLow), };

}


- (void) stopRecordingOnAudioRecorder:(AVAudioRecorder *)paramRecorder{

    /* Just stop the audio recorder here */

    [paramRecorder stop];

}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{

    if (flag){

        NSLog(@"Successfully stopped the audio recording process.");

        /* Let's try to retrieve the data for the recorded file */

        NSError *playbackError = nil;

        NSError *readingError = nil;

        NSData  *fileData =

        [NSData dataWithContentsOfURL:[self audioRecordingPath]

                              options:NSDataReadingMapped

                                error:&readingError];

        /* Form an audio player and make it play the recorded data */

        self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData

                                                         error:&playbackError];

        /* Could we instantiate the audio player? */

        if (self.audioPlayer != nil){

            self.audioPlayer.delegate = self;

            /* Prepare to play and start playing */

            if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){

                NSLog(@"Started playing the recorded audio.");

            } else {

                NSLog(@"Could not play the audio.");

            }

        } else {

            NSLog(@"Failed to create an audio player.");

        }

    } else {

        NSLog(@"Stopping the audio recording failed.");

    }

    /* Here we don't need the audio recorder anymore */

    self.audioRecorder = nil;

}


- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{

    if (flag){

        NSLog(@"Audio player stopped correctly.");

    } else {

        NSLog(@"Audio player did not stop correctly.");

    }

    if ([player isEqual:self.audioPlayer]){

        self.audioPlayer = nil;

    } else {

        /* This is not our player */

    }

}


- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{

    /* The audio session has been deactivated here */

}


- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player

                       withOptions:(NSUInteger)flags{

    if (flags == AVAudioSessionInterruptionOptionShouldResume){

        [player play];

    }

}



@end


打印:

2014-06-27 16:00:07.256 cookbook7_12[1116:a0b] Successfully started to record.

2014-06-27 16:00:12.260 cookbook7_12[1116:a0b] Successfully stopped the audio recording process.

2014-06-27 16:00:12.272 cookbook7_12[1116:a0b] Started playing the recorded audio.

2014-06-27 16:00:17.253 cookbook7_12[1116:a0b] Audio player stopped correctly.


12.4. Handling Interruptions While Recording Audio

录音过程中突然来电话了,电话后如何继续录呢


- (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder{

    NSLog(@"Recording process is interrupted");

}

- (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder withOptions:(NSUInteger)flags{

    if (flags == AVAudioSessionInterruptionOptionShouldResume){

        NSLog(@"Resuming the recording...");
        [recorder record];

    }

}

使用方法更播放音频的一样


12.5. Playing Audio over Other Active Sounds

播放音频,但不停止其他应用的音频

修改12.1.的代码


-(void)testPlayMP3

{

    //增加的部分 beign

    NSError *audioSessionError = nil;

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];

    if ([audioSession setCategory:AVAudioSessionCategoryAmbient error:&audioSessionError]){

        NSLog(@"Successfully set the audio session.");

    } else {

        NSLog(@"Could not set the audio session");

    }

    //增加的部分 end

    

    dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(dispatchQueue, ^(void) {

        NSBundle *mainBundle = [NSBundle mainBundle];

        NSString *filePath = [mainBundle pathForResource:@"MySong"

                                                  ofType:@"mp3"];

        NSData   *fileData = [NSData dataWithContentsOfFile:filePath];

        NSError  *error = nil;

        /* Start the audio player */

        self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData

                                                         error:&error];

        /* Did we get an instance of AVAudioPlayer? */

        if (self.audioPlayer != nil){

            /* Set the delegate and start playing */

            self.audioPlayer.delegate = self;

            if ([self.audioPlayer prepareToPlay] &&

                [self.audioPlayer play]){

                /* Successfully started playing */

                NSLog(@"Successfully started playing");

            } else {

                /* Failed to play */

                NSLog(@"Failed to play");

            }

        } else {

            /* Failed to instantiate AVAudioPlayer */

            NSLog(@"Failed to instantiate AVAudioPlayer ");

        }

    });

}


#pragma mark -- Values for the category property --


/*  Use this category for background sounds such as rain, car engine noise, etc.  

 Mixes with other music. */

AVF_EXPORT NSString *const AVAudioSessionCategoryAmbient;

/*  Use this category for background sounds.  Other music will stop playing. */

AVF_EXPORT NSString *const AVAudioSessionCategorySoloAmbient;


/* Use this category for music tracks.*/

AVF_EXPORT NSString *const AVAudioSessionCategoryPlayback;


/*  Use this category when recording audio. */

AVF_EXPORT NSString *const AVAudioSessionCategoryRecord;


/*  Use this category when recording and playing back audio. */

AVF_EXPORT NSString *const AVAudioSessionCategoryPlayAndRecord;


/*  Use this category when using a hardware codec or signal processor while

 not playing or recording audio. */

AVF_EXPORT NSString *const AVAudioSessionCategoryAudioProcessing;


/*  Use this category to customize the usage of available audio accessories and built-in audio hardware.

 For example, this category provides an application with the ability to use an available USB output 

 and headphone output simultaneously for separate, distinct streams of audio data. Use of 

 this category by an application requires a more detailed knowledge of, and interaction with, 

 the capabilities of the available audio routes.  May be used for input, output, or both.

 Note that not all output types and output combinations are eligible for multi-route.  Input is limited

 to the last-in input port. Eligible inputs consist of the following:

AVAudioSessionPortUSBAudio, AVAudioSessionPortHeadsetMic, and AVAudioSessionPortBuiltInMic.  

 Eligible outputs consist of the following: 

AVAudioSessionPortUSBAudio, AVAudioSessionPortLineOut, AVAudioSessionPortHeadphones, AVAudioSessionPortHDMI, 

and AVAudioSessionPortBuiltInSpeaker.  

 Note that AVAudioSessionPortBuiltInSpeaker is only allowed to be used when there are no other eligible 

 outputs connected.  */

AVF_EXPORT NSString *const AVAudioSessionCategoryMultiRoute NS_AVAILABLE_IOS(6_0);



12.6. Playing Video Files

播放视频文件


#import <MediaPlayer/MediaPlayer.h>


@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;



- (IBAction)buttonAction:(id)sender {

    [self startPlayingVideo:nil];

}


- (void) startPlayingVideo:(id)paramSender{

    /* First let's construct the URL of the file in our application bundle

     that needs to get played by the movie player */

    NSBundle *mainBundle = [NSBundle mainBundle];

    NSURL *url = [mainBundle URLForResource:@"Sample"

                              withExtension:@"m4v"];

    /* If we have already created a movie player before,

     let's try to stop it */

    if (self.moviePlayer != nil){

        [self stopPlayingVideo:nil];

    }

    /* Now create a new movie player using the URL */

    self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];

    if (self.moviePlayer != nil){

        /* Listen for the notification that the movie player sends us whenever it finishes playing an audio file */

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoHasFinishedPlaying:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];

        NSLog(@"Successfully instantiated the movie player.");

        /* Scale the movie player to fit the aspect ratio */

        self.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;

        [self.view addSubview:self.moviePlayer.view];

        [self.moviePlayer setFullscreen:YES

                               animated:NO];

        /* Let's start playing the video in full screen mode */

        [self.moviePlayer play];


    } else {

        NSLog(@"Failed to instantiate the movie player.");

    }

}


- (void) stopPlayingVideo:(id)paramSender {

    if (self.moviePlayer != nil){

        [[NSNotificationCenter defaultCenter]

         removeObserver:self

         name:MPMoviePlayerPlaybackDidFinishNotification

         object:self.moviePlayer];

        [self.moviePlayer stop];

        [self.moviePlayer.view removeFromSuperview];

    }

}

- (void) videoHasFinishedPlaying:(NSNotification *)paramNotification{

    /* Find out what the reason was for the player to stop */

    NSNumber *reason =

    paramNotification.userInfo

    [MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];

    if (reason != nil){

        NSInteger reasonAsInteger = [reason integerValue];

        switch (reasonAsInteger){

            case MPMovieFinishReasonPlaybackEnded:{

                /* The movie ended normally */

                break; }

            case MPMovieFinishReasonPlaybackError:{

                /* An error happened and the movie ended */ break;

            }

            case MPMovieFinishReasonUserExited:{

                /* The user exited the player */

                break; }

        }

        NSLog(@"Finish Reason = %ld", (long)reasonAsInteger);

        [self stopPlayingVideo:nil];

    }

}


打印:

2014-06-30 11:56:25.126 cookbook7_12[606:a0b] Successfully instantiated the movie player.

2014-06-30 11:56:31.551 cookbook7_12[606:a0b] Finish Reason = 0


实测中我拿了一个MP4文件来测的,把MP4重命名成Sample.m4v,结果正常播放




如果你嫌太复杂,好吧,来个简单的,但是自由度就没那么高了

- (IBAction)buttonAction:(id)sender {

    [self testMPMoviePlayerViewController];

//    [self startPlayingVideo:nil];

}


-(void)testMPMoviePlayerViewController{

//    NSString * path = 

    NSURL * url = [[NSBundle mainBundle] URLForResource:@"Sample" withExtension:@"m4v"];

    MPMoviePlayerViewController * player = [[MPMoviePlayerViewController alloc] initWithContentURL:url];

    [self presentMoviePlayerViewControllerAnimated:player];

}



12.7. Capturing Thumbnails from Video Files

异步获取截图,异步是指截图时不卡屏

方法:requestThumbnailImagesAtTimes:timeOption:


在上一节中做点修改


- (void) startPlayingVideo:(id)paramSender{

    /* First let's construct the URL of the file in our application bundle

     that needs to get played by the movie player */

    NSBundle *mainBundle = [NSBundle mainBundle];

    NSURL *url = [mainBundle URLForResource:@"Sample"

                              withExtension:@"m4v"];

    /* If we have already created a movie player before,

     let's try to stop it */

    if (self.moviePlayer != nil){

        [self stopPlayingVideo:nil];

    }

    /* Now create a new movie player using the URL */

    self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];

    if (self.moviePlayer != nil){

        /* Listen for the notification that the movie player sends us whenever it finishes playing an audio file */

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoHasFinishedPlaying:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];

        //增加截图观察者

        [[NSNotificationCenter defaultCenter]

         addObserver:self selector:@selector(videoThumbnailIsAvailable:) name:MPMoviePlayerThumbnailImageRequestDidFinishNotification object:self.moviePlayer];

        

        NSLog(@"Successfully instantiated the movie player.");

        /* Scale the movie player to fit the aspect ratio */

        self.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;

        [self.view addSubview:self.moviePlayer.view];

        [self.moviePlayer setFullscreen:YES

                               animated:NO];

        /* Let's start playing the video in full screen mode */

        [self.moviePlayer play];

        

        //3秒的位置截图,不是3秒后截图

        /* Capture the frame at the third second into the movie */

        NSNumber *thirdSecondThumbnail = @3.0f;

        /* We can ask to capture as many frames as we

         want. But for now, we are just asking to capture one frame */

        /* Ask the movie player to capture this frame for us */

        [self.moviePlayer

         requestThumbnailImagesAtTimes:@[thirdSecondThumbnail]

         timeOption:MPMovieTimeOptionExact];

    } else {

        NSLog(@"Failed to instantiate the movie player.");

    }

}


//处理截图通知

- (void) videoThumbnailIsAvailable:(NSNotification *)paramNotification{

    MPMoviePlayerController *controller = [paramNotification object];

    if ([controller isEqual:self.moviePlayer]){

        NSLog(@"Thumbnail is available");

        /* Now get the thumbnail out of the user info dictionary */

        UIImage *thumbnail = [paramNotification.userInfo objectForKey:MPMoviePlayerThumbnailImageKey];

        if (thumbnail != nil){

            /* We got the thumbnail image. You can now use it here */

            NSLog(@"thumbnail=%@",thumbnail);

        }

    }

}


打印:

2014-06-30 15:54:03.094 cookbook7_12[612:a0b] Successfully instantiated the movie player.

2014-06-30 15:54:03.349 cookbook7_12[612:a0b] Thumbnail is available

2014-06-30 15:54:03.349 cookbook7_12[612:a0b] thumbnail=<UIImage: 0x10ae541c0>

2014-06-30 15:54:09.602 cookbook7_12[612:a0b] Finish Reason = 0


12.8. Accessing the Music Library

访问音乐库



#import "MediaPickerViewController.h"

#import <MediaPlayer/MediaPlayer.h>

#import <AVFoundation/AVFoundation.h>


@interface MediaPickerViewController ()<MPMediaPickerControllerDelegate,AVAudioPlayerDelegate>


@property (nonatomic, strong) MPMusicPlayerController *myMusicPlayer;

@property (nonatomic, strong) UIButton *buttonPickAndPlay;

@property (nonatomic, strong) UIButton *buttonStopPlaying;

@property (nonatomic, strong) MPMediaPickerController *mediaPicker;


- (IBAction)displayMediaPickerAndPlayItem:(id)sender;

- (IBAction)stopPlayingAudio:(id)sender;


@end


@implementation MediaPickerViewController


- (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.

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (IBAction)displayMediaPickerAndPlayItem:(id)sender {

    self.mediaPicker =[[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeAnyAudio];

    if (self.mediaPicker != nil){

        NSLog(@"Successfully instantiated a media picker.");

        self.mediaPicker.delegate = self;

        self.mediaPicker.allowsPickingMultipleItems = YES;

        self.mediaPicker.showsCloudItems = YES;

        self.mediaPicker.prompt = @"Pick a song please...";

        [self.view addSubview:self.mediaPicker.view];

        [self.navigationController presentViewController:self.mediaPicker

                                                animated:YES

                                              completion:nil];

    }else{

        NSLog(@"Could not instantiate a media picker.");

    }

}


- (IBAction)stopPlayingAudio:(id)sender {

    if (self.myMusicPlayer != nil){

        [[NSNotificationCenter defaultCenter]

            removeObserver:self

            name:MPMusicPlayerControllerPlaybackStateDidChangeNotification

            object:self.myMusicPlayer];

        [[NSNotificationCenter defaultCenter]

            removeObserver:self

            name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification

            object:self.myMusicPlayer];

        [[NSNotificationCenter defaultCenter]

            removeObserver:self

            name:MPMusicPlayerControllerVolumeDidChangeNotification

            object:self.myMusicPlayer];

        [self.myMusicPlayer stop];

    }

}


- (void) mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{

    NSLog(@"Media Picker returned");

    /* First, if we have already created a music player, let's

     deallocate it */

    self.myMusicPlayer = nil;

    self.myMusicPlayer = [[MPMusicPlayerController alloc] init];

    [self.myMusicPlayer beginGeneratingPlaybackNotifications];

    /* Get notified when the state of the playback changes */

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(musicPlayerStateChanged:)

                                                 name:MPMusicPlayerControllerPlaybackStateDidChangeNotification

                                               object:self.myMusicPlayer];

    /* Get notified when the playback moves from one item

     to the other. In this recipe, we are only going to allow

     our user to pick one music file */

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(nowPlayingItemIsChanged:)

                                                 name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification

                                               object:self.myMusicPlayer];

    /* And also get notified when the volume of the

     music player is changed */

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(volumeIsChanged:)

                                                 name:MPMusicPlayerControllerVolumeDidChangeNotification

                                               object:self.myMusicPlayer];

    /* Start playing the items in the collection */

    [self.myMusicPlayer setQueueWithItemCollection:mediaItemCollection];

    [self.myMusicPlayer play];

    /* Finally dismiss the media picker controller */

    [mediaPicker dismissViewControllerAnimated:YES completion:nil];

}


- (void) mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{

    /* The media picker was cancelled */

    NSLog(@"Media Picker was cancelled");

    [mediaPicker dismissViewControllerAnimated:YES completion:nil];

}


- (void) musicPlayerStateChanged:(NSNotification *)paramNotification{

    NSLog(@"Player State Changed");

    /* Let's get the state of the player */

    NSNumber *stateAsObject =[paramNotification.userInfo objectForKey:@"MPMusicPlayerControllerPlaybackStateKey"];

    NSInteger state = [stateAsObject integerValue];

    /* Make your decision based on the state of the player */

    switch (state){

        case MPMusicPlaybackStateStopped:{

            /* Here the media player has stopped playing the queue. */

            break; }

        case MPMusicPlaybackStatePlaying:{

            /* The media player is playing the queue. Perhaps you

             can reduce some processing that your application

             that is using to give more processing power

             to the media player */

            break; }

        case MPMusicPlaybackStatePaused:{

            /* The media playback is paused here. You might want

             to indicate by showing graphics to the user */

            break; }

        case MPMusicPlaybackStateInterrupted:{

            /* An interruption stopped the playback of the media queue */ break;

        }

        case MPMusicPlaybackStateSeekingForward:{

            /* The user is seeking forward in the queue */

            break; }

        case MPMusicPlaybackStateSeekingBackward:{

            /* The user is seeking backward in the queue */ break;

        }

    } /* switch (State){ */

}


- (void) nowPlayingItemIsChanged:(NSNotification *)paramNotification{

    NSLog(@"Playing Item Is Changed");

    NSString *persistentID =[paramNotification.userInfo objectForKey:@"MPMusicPlayerControllerNowPlayingItemPersistentIDKey"];

    /* Do something with Persistent ID */

    NSLog(@"Persistent ID = %@", persistentID);

}


- (void) volumeIsChanged:(NSNotification *)paramNotification{

    NSLog(@"Volume Is Changed");

    /* The userInfo dictionary of this notification is normally empty */

}


@end


打印:

2014-06-30 16:52:08.897 cookbook7_12[247:907] Successfully instantiated a media picker.




















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值