在IOS中使用AVPlayer去播放在線音頻文件,並設置音量
在這裏給AVPlayer播放在線音頻文件作個記號
1.在H文件中初始:==============
AVPlayer *mp3Player;
AVPlayerItem *mp3PlayerItem;
id audioMix;
id volumeMixInput;
2.在MM文件中:
//作品播放
NSURL * songUrl = [NSURL URLWithString:userInfo.songUrl];
AVURLAsset *movieAsset = [[[AVURLAsset alloc]initWithURL:songUrl options:nil]autorelease];
self. mp3PlayerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
[self. mp3PlayerItem addObserver:self forKeyPath:@"status" options:0 context:NULL];
self. mp3Player = [AVPlayer playerWithPlayerItem:self. mp3PlayerItem];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self. mp3Player];
playerLayer.frame = self.view.layer.bounds;
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.view.layer addSublayer:playerLayer];
[self. mp3Player setAllowsExternalPlayback:YES];
3.實現代理方法:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"status"])
{
if (AVPlayerItemStatusReadyToPlay == self. mp3Player.currentItem.status)
{
[self. mp3Player play];
}
}
}
4.現實音量調整
-(void) setVolume:(float)volume{
//作品音量控制
NSMutableArray *allAudioParams = [NSMutableArray array];
AVMutableAudioMixInputParameters *audioInputParams =[AVMutableAudioMixInputParameters audioMixInputParameters];
[audioInputParams setVolume:volume atTime:kCMTimeZero];
[audioInputParams setTrackID:1];
[allAudioParams addObject:audioInputParams];
audioMix = [AVMutableAudioMix audioMix];
[audioMix setInputParameters:allAudioParams];
[self. mp3PlayerItem setAudioMix:audioMix]; // Mute the player item
[avAudioPlayer setVolume:volume];
}
5.取得播放時間
- (NSTimeInterval) playableDuration
{
AVPlayerItem * item = self.worksPlayer.currentItem;
if (item.status == AVPlayerItemStatusReadyToPlay) {
return CMTimeGetSeconds(self.worksPlayer.currentItem.duration);
}
else
{
return(CMTimeGetSeconds(kCMTimeInvalid));
}
}
- (NSTimeInterval) playableCurrentTime
{
AVPlayerItem * item = self.worksPlayer.currentItem;
if (item.status == AVPlayerItemStatusReadyToPlay) {
NSLog(@"%f\n",CMTimeGetSeconds(self.worksPlayer.currentItem.currentTime));
if (!playBeginState&&CMTimeGetSeconds(self.worksPlayer.currentItem.currentTime)==CMTimeGetSeconds(self.worksPlayer.currentItem.duration)) {
[streamer stop];
}
playBeginState = NO;
return CMTimeGetSeconds(self.worksPlayer.currentItem.currentTime);
}
else
{
return(CMTimeGetSeconds(kCMTimeInvalid));
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.