在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 ));
}
}
转载于:https://blog.51cto.com/2119784/1102353