IOS支持的音频格式AAC,ALAC,IMA4,linear,MP3,caf(苹果推荐格式),在使用音频时需要引入AVFoundation.framework,然后使用
AVAudioPlayer类:
AVAudioPlayer *audioplayer;
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"没那么简单" ofType:@"mp3"]; NSURL *url = [[NSURL alloc]initFileURLWithPath:filePath]; audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; audioplayer.volume = 0.5; [audioplayer prepareToPlay]; audioplayer.numberOfLoops = -1; audioplayer.delegate = self;
还可以同过MediaPlayer.framework里的MPMusicPlayerController类来播放ipod库中自带的音乐,使用时要先使用
MPMediaPickerController从库中选择歌曲。
MPMusicPlayerController *musicPlayer;
UIDevice *device = [UIDevice currentDevice]; NSString *model = [device model]; NSLog(@"%@",[device model]); if([model isEqualToString:@"iPhone Simulator"] == NO) { MPMediaPickerController *pickController = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic]; [pickController setDelegate:self]; pickController.prompt = @"选取歌曲";//在navgationController中页可以通过设置prompt属性增加一个提示标题,当设置prompt属性后,navgationbar上会多出一行区域用于显示prompt。prompt:提示 [pickController setAllowsPickingMultipleItems:YES]; [self presentModalViewController:pickController animated:YES]; }
视频部分主要是用MediaPlayer.framework的MPMoviePlayerViewController类来播放,这里要说一下MPMoviePlayerViewController和MPMoviePlayerController的区别,苹果起初用MPMoviePlayerController播放视频,但是MPMoviePlayerController只能进行全屏播放,很不方便,后来苹果就加入了MPMoviePlayerViewController。但是这个累的API相当简单,只有一个MPMoviePlayerController类的moviePlayer属性。但是现在已经可以通过设置moviePlayer的view属性来进行窗口播放了
[moviePlayer.moviePlayer viewsetFrame:CGRectMake(10, 10, 300, 300)];
NSString * filePath = [[NSBundle mainBundle] pathForResource:@"tta" ofType:@"mp4"]; NSURL * url = [NSURL fileURLWithPath:filePath]; moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:url]; [moviePlayer.moviePlayer setShouldAutoplay:NO]; [moviePlayer.moviePlayer setControlStyle:MPMovieControlStyleNone]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];