IOS利用AVPlayer开发多媒体在线播放器

时间:2022-06-26 03:20:40

在这里给AVPlayer播放在线音频文件作个记号

1.在H文件中初始:

==============
AVPlayer *mp3Player;
AVPlayerItem *mp3PlayerItem;
id audioMix;
id volumeMixInput;

2.在MM文件中:


view sourceprint?01.//作品播放02.NSURL * songUrl = [NSURL URLWithString:userInfo.songUrl];03.AVURLAsset *movieAsset    = [[[AVURLAsset alloc]initWithURL:songUrl options:nil]autorelease];04. 05. 06.self. mp3PlayerItem = [AVPlayerItem playerItemWithAsset:movieAsset];07.[self. mp3PlayerItem addObserver:self forKeyPath:@"status" options:0context:NULL];08.self. mp3Player = [AVPlayer playerWithPlayerItem:self. mp3PlayerItem];09.AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self. mp3Player];10.playerLayer.frame = self.view.layer.bounds;11.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;12.[self.view.layer addSublayer:playerLayer];13.[self. mp3Player setAllowsExternalPlayback:YES];


3.实现代理方法:

 

view sourceprint?01.- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context02.{03.if ([keyPath isEqualToString:@"status"])04.{05.if (AVPlayerItemStatusReadyToPlay == self. mp3Player.currentItem.status)06.{07.[self. mp3Player play];08.}09.}10.}


4.现实音量调整

 

view sourceprint?01.-(void) setVolume:(float)volume{02.//作品音量控制03.NSMutableArray *allAudioParams = [NSMutableArray array];04.AVMutableAudioMixInputParameters *audioInputParams =[AVMutableAudioMixInputParameters audioMixInputParameters];05.[audioInputParams setVolume:volume atTime:kCMTimeZero];06.[audioInputParams setTrackID:1];07.[allAudioParams addObject:audioInputParams];08.audioMix = [AVMutableAudioMix audioMix];09.[audioMix setInputParameters:allAudioParams];10.[self. mp3PlayerItem setAudioMix:audioMix]; // Mute the player item11. 12.[avAudioPlayer setVolume:volume];13.}


5.取得播放时间

 

view sourceprint?01.- (NSTimeInterval) playableDuration02.{03.AVPlayerItem * item = self.worksPlayer.currentItem;04.if (item.status == AVPlayerItemStatusReadyToPlay) {05.return CMTimeGetSeconds(self.worksPlayer.currentItem.duration);06.}07.else08.{09.return(CMTimeGetSeconds(kCMTimeInvalid));10.}11.}12.- (NSTimeInterval) playableCurrentTime13.{14.AVPlayerItem * item = self.worksPlayer.currentItem;15. 16.if (item.status == AVPlayerItemStatusReadyToPlay) {17.NSLog(@"%f\n",CMTimeGetSeconds(self.worksPlayer.currentItem.currentTime));18.if(!playBeginState&&CMTimeGetSeconds(self.worksPlayer.currentItem.currentTime)==CMTimeGetSeconds(self.worksPlayer.currentItem.duration)) {19.[streamer stop];20.}21.playBeginState = NO;22.return CMTimeGetSeconds(self.worksPlayer.currentItem.currentTime);23.}24.else25.{26.return(CMTimeGetSeconds(kCMTimeInvalid));27.}28.}