12.0~12.8 Audio and Videl 音频和视频
来源:互联网 发布:windows 8 apart from 编辑:程序博客网 时间:2024/06/05 01:34
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
{
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)buttonAction:(id)sender {
[selftestPlayMP3];
}
-(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 = [[AVAudioPlayeralloc] 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.audioPlayerprepareToPlay] &&
[self.audioPlayerplay]){
/* 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
{
[superviewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)buttonAction:(id)sender {
[selftestReocrder];
}
-(void)testReocrder
{
AVAudioSession *session = [AVAudioSessionsharedInstance];
[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.");
}
*/
//所以我就干脆直接这样子了,结果还是可以录制的
[selfstartRecordingAudio];
}
- (void) startRecordingAudio{
NSError *error = nil;
NSURL *audioRecordingURL = [self audioRecordingPath];
self.audioRecorder = [[AVAudioRecorderalloc]
initWithURL:audioRecordingURL
settings:[selfaudioRecordingSettings]
error:&error];
if (self.audioRecorder !=nil){
self.audioRecorder.delegate =self;
/* Prepare the recorder and then start the recording */
if ([self.audioRecorderprepareToRecord] && [self.audioRecorderrecord]){
NSLog(@"Successfully started to record.");
/* After 5 seconds, let's stop the recording process */
[selfperformSelector:@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 = [[NSFileManageralloc] 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 */
[paramRecorderstop];
}
- (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 =
[NSDatadataWithContentsOfURL:[selfaudioRecordingPath]
options:NSDataReadingMapped
error:&readingError];
/* Form an audio player and make it play the recorded data */
self.audioPlayer = [[AVAudioPlayeralloc] 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.audioPlayerprepareToPlay] && [self.audioPlayerplay]){
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 = [AVAudioSessionsharedInstance];
if ([audioSession setCategory:AVAudioSessionCategoryAmbienterror:&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 = [[AVAudioPlayeralloc] 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.audioPlayerprepareToPlay] &&
[self.audioPlayerplay]){
/* 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_EXPORTNSString *const AVAudioSessionCategoryAmbient;
/* Use this category for background sounds. Other music will stop playing. */
AVF_EXPORTNSString *const AVAudioSessionCategorySoloAmbient;
/* Use this category for music tracks.*/
AVF_EXPORTNSString *const AVAudioSessionCategoryPlayback;
/* Use this category when recording audio. */
AVF_EXPORTNSString *const AVAudioSessionCategoryRecord;
/* Use this category when recording and playing back audio. */
AVF_EXPORTNSString *const AVAudioSessionCategoryPlayAndRecord;
/* Use this category when using a hardware codec or signal processor while
not playing or recording audio. */
AVF_EXPORTNSString *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_EXPORTNSString *const AVAudioSessionCategoryMultiRouteNS_AVAILABLE_IOS(6_0);
12.6. Playing Video Files
播放视频文件
#import <MediaPlayer/MediaPlayer.h>
@property (nonatomic,strong) MPMoviePlayerController *moviePlayer;
- (IBAction)buttonAction:(id)sender {
[selfstartPlayingVideo: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){
[selfstopPlayingVideo:nil];
}
/* Now create a new movie player using the URL */
self.moviePlayer = [[MPMoviePlayerControlleralloc] initWithContentURL:url];
if (self.moviePlayer !=nil){
/* Listen for the notification that the movie player sends us whenever it finishes playing an audio file */
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(videoHasFinishedPlaying:)name:MPMoviePlayerPlaybackDidFinishNotificationobject:self.moviePlayer];
NSLog(@"Successfully instantiated the movie player.");
/* Scale the movie player to fit the aspect ratio */
self.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
[self.viewaddSubview:self.moviePlayer.view];
[self.moviePlayersetFullscreen:YES
animated:NO];
/* Let's start playing the video in full screen mode */
[self.moviePlayerplay];
} else {
NSLog(@"Failed to instantiate the movie player.");
}
}
- (void) stopPlayingVideo:(id)paramSender {
if (self.moviePlayer !=nil){
[[NSNotificationCenterdefaultCenter]
removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.moviePlayer];
[self.moviePlayerstop];
[self.moviePlayer.viewremoveFromSuperview];
}
}
- (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 {
[selftestMPMoviePlayerViewController];
// [self startPlayingVideo:nil];
}
-(void)testMPMoviePlayerViewController{
// NSString * path =
NSURL * url = [[NSBundlemainBundle] URLForResource:@"Sample"withExtension:@"m4v"];
MPMoviePlayerViewController * player = [[MPMoviePlayerViewControlleralloc] initWithContentURL:url];
[selfpresentMoviePlayerViewControllerAnimated: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 = [NSBundlemainBundle];
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){
[selfstopPlayingVideo:nil];
}
/* Now create a new movie player using the URL */
self.moviePlayer = [[MPMoviePlayerControlleralloc] initWithContentURL:url];
if (self.moviePlayer !=nil){
/* Listen for the notification that the movie player sends us whenever it finishes playing an audio file */
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(videoHasFinishedPlaying:)name:MPMoviePlayerPlaybackDidFinishNotificationobject:self.moviePlayer];
//增加截图观察者
[[NSNotificationCenterdefaultCenter]
addObserver:selfselector:@selector(videoThumbnailIsAvailable:)name:MPMoviePlayerThumbnailImageRequestDidFinishNotificationobject:self.moviePlayer];
NSLog(@"Successfully instantiated the movie player.");
/* Scale the movie player to fit the aspect ratio */
self.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
[self.viewaddSubview:self.moviePlayer.view];
[self.moviePlayersetFullscreen:YES
animated:NO];
/* Let's start playing the video in full screen mode */
[self.moviePlayerplay];
//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 = [paramNotificationobject];
if ([controller isEqual:self.moviePlayer]){
NSLog(@"Thumbnail is available");
/* Now get the thumbnail out of the user info dictionary */
UIImage *thumbnail = [paramNotification.userInfoobjectForKey: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
{
[superviewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)displayMediaPickerAndPlayItem:(id)sender {
self.mediaPicker =[[MPMediaPickerControlleralloc] 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.viewaddSubview:self.mediaPicker.view];
[self.navigationControllerpresentViewController:self.mediaPicker
animated:YES
completion:nil];
}else{
NSLog(@"Could not instantiate a media picker.");
}
}
- (IBAction)stopPlayingAudio:(id)sender {
if (self.myMusicPlayer !=nil){
[[NSNotificationCenterdefaultCenter]
removeObserver:self
name:MPMusicPlayerControllerPlaybackStateDidChangeNotification
object:self.myMusicPlayer];
[[NSNotificationCenterdefaultCenter]
removeObserver:self
name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object:self.myMusicPlayer];
[[NSNotificationCenterdefaultCenter]
removeObserver:self
name:MPMusicPlayerControllerVolumeDidChangeNotification
object:self.myMusicPlayer];
[self.myMusicPlayerstop];
}
}
- (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 = [[MPMusicPlayerControlleralloc] init];
[self.myMusicPlayerbeginGeneratingPlaybackNotifications];
/* Get notified when the state of the playback changes */
[[NSNotificationCenterdefaultCenter] 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 */
[[NSNotificationCenterdefaultCenter] addObserver:self
selector:@selector(nowPlayingItemIsChanged:)
name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object:self.myMusicPlayer];
/* And also get notified when the volume of the
music player is changed */
[[NSNotificationCenterdefaultCenter] addObserver:self
selector:@selector(volumeIsChanged:)
name:MPMusicPlayerControllerVolumeDidChangeNotification
object:self.myMusicPlayer];
/* Start playing the items in the collection */
[self.myMusicPlayersetQueueWithItemCollection:mediaItemCollection];
[self.myMusicPlayerplay];
/* Finally dismiss the media picker controller */
[mediaPicker dismissViewControllerAnimated:YEScompletion:nil];
}
- (void) mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{
/* The media picker was cancelled */
NSLog(@"Media Picker was cancelled");
[mediaPicker dismissViewControllerAnimated:YEScompletion:nil];
}
- (void) musicPlayerStateChanged:(NSNotification *)paramNotification{
NSLog(@"Player State Changed");
/* Let's get the state of the player */
NSNumber *stateAsObject =[paramNotification.userInfoobjectForKey:@"MPMusicPlayerControllerPlaybackStateKey"];
NSInteger state = [stateAsObject integerValue];
/* Make your decision based on the state of the player */
switch (state){
caseMPMusicPlaybackStateStopped:{
/* Here the media player has stopped playing the queue. */
break; }
caseMPMusicPlaybackStatePlaying:{
/* 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; }
caseMPMusicPlaybackStatePaused:{
/* The media playback is paused here. You might want
to indicate by showing graphics to the user */
break; }
caseMPMusicPlaybackStateInterrupted:{
/* An interruption stopped the playback of the media queue */break;
}
caseMPMusicPlaybackStateSeekingForward:{
/* The user is seeking forward in the queue */
break; }
caseMPMusicPlaybackStateSeekingBackward:{
/* The user is seeking backward in the queue */break;
}
} /* switch (State){ */
}
- (void) nowPlayingItemIsChanged:(NSNotification *)paramNotification{
NSLog(@"Playing Item Is Changed");
NSString *persistentID =[paramNotification.userInfoobjectForKey:@"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.
- 12.0~12.8 Audio and Videl 音频和视频
- html5 音频和视频(audio And video)
- HTML5-音频audio和视频video标签
- IOS音频和视频(Audio & Video)
- 视频<video>音频<audio>
- HTML5 网页音频和视频(<audio> 和 <video>)
- 音频与视频标签—audio和video
- 音频压缩和编解码(Audio Compression and Codec)
- HTML5 音频播放 <audio> 视频<video>
- HTML5(2):音频(audio)与视频(video)
- H5之视频video/音频audio
- HTML5视频播放器video和音频播放器audio用法
- HTML5视频播放器<video>和音频播放器<audio>用法
- H5新属性audio音频和 video视频的控制详解(controls)
- Html5新属性audio音频和video视频的控制详解(controls)
- Html5之audio音频和video视频的控制详解(controls)
- 音频Audio
- 音频audio
- 转置-置换-向量空间R
- 程序员的20个常见瓶颈
- 斐波那契数列
- android开发中代码片段集合
- 数组移动
- 12.0~12.8 Audio and Videl 音频和视频
- HTML5未来发展的六大趋势
- 顺序表,链表,静态链表的建立以及插入和删除操作
- Jump Game
- Java高级之反射
- 使用Java 注解
- 【JAVA学习】轻量级与重量级
- angularjs 一些概念说明
- FindBugs 的使用