目录
1. AudioServicesPlaySystemSound
2. AVAudioPlayer
3. AVPlayerViewController
4. AVPlayer
1. AudioServicesPlaySystemSound
系统音
#import
1.用于播放不超过30秒的声音
2.它支持的文件格式有限
3.没有提供操作声音和控制音量的功能
播放/震动
// 提示音
AudioServicesPlaySystemSound(1007);
// 提示音+震动
AudioServicesPlayAlertSound(1007);
// 震动
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate));
自定义音频
1.时间不能超过30秒
2.数据必须是PCM或者IMA4流格式
3.必须被打包成三个格式之一:Core Audio Format (.caf), Waveform audio (.wav), Audio Interchange File (.aiff)
步骤:
1.导入音频
2.Code
// 获取音频ID
SystemSoundID soundID;
NSURL *fileUrl=[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"1.wav" ofType:nil]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl),&soundID);
// 播放
AudioServicesPlaySystemSound(soundID);
2. AVAudioPlayer
- 播放
// 设置后台可播放(当被打断进入后台时)
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
// AVAudioPlayer : NSObject
// 创建音频播放器
// 创建方式一
NSError *error;
AVAudioPlayer *audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:@""] error:&error];
// 创建方式二
// AVAudioPlayer *audioPlayer=[[AVAudioPlayer alloc]initWithData:[NSData data] error:&error];
if(!error){
// 播放次数(-1:无限)
[audioPlayer setNumberOfLoops:-1];
// 音量(0~1)
[audioPlayer setVolume:1];
// 速率(1:原速度)
[audioPlayer setRate:1.0];
// 使速率有效(必须在prepare之前)
[audioPlayer setEnableRate:true];
// 预播放
[audioPlayer prepareToPlay];
}
// 总时长
NSTimeInterval allTime=audioPlayer.duration;
// 当前已播放时长
NSTimeInterval currentTime=audioPlayer.currentTime;
// 是否正在播放
BOOL isPlaying=[audioPlayer isPlaying];
// 暂停
[audioPlayer pause];
// 播放
[audioPlayer play];
// 停止
[audioPlayer stop];
dele
// dele
[audioPlayer setDelegate:self];
#pragma mark AVAudioPlayerDelegate
// 播放完成后调用
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
if(flag){ // 播放成功
}
}
// 解码发生错误时调用
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error{
}
// 应用被打断时(如:来电话)调用
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{}
// 应用被打断后,返回应用时调用
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags{}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withFlags:(NSUInteger)flags{}
// 没有实现audioPlayerEndInterruption:withFlags:时调用
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player{}
- 录音
// 创建会话
AVAudioSession *audioSession=[AVAudioSession sharedInstance];
//
NSError *error;
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
AVAudioRecorder *audioRecorder;
if(!error){
// 创建录音(路径,参数:声音采样率,编码格式,采集音轨,音频质量)
audioRecorder=[[AVAudioRecorder alloc]initWithURL:[self directoryPath] settings:@{AVSampleRateKey:@(44100),AVFormatIDKey:@(kAudioFormatMPEG4AAC),AVNumberOfChannelsKey:@(1),AVEncoderAudioQualityKey:@(AVAudioQualityMedium)} error:&error];
if(!error){
// 预处理
[audioRecorder prepareToRecord];
}
}
// 是否正在录音
BOOL isRecording=[audioRecorder isRecording];
// 开始录音
[audioSession setActive:true error:&error];
if(!error){
[audioRecorder record];
}
// 停止录音
[audioRecorder stop];
[audioSession setActive:false error:&error];
if(!error){
}
// 返回音频路径
-(NSURL *)directoryPath{
// 音频名
NSDateFormatter *dateFormat=[NSDateFormatter new];
[dateFormat setDateFormat:@"ddMMyyyyhhmmss"];
NSString *recordPath=[NSString stringWithFormat:@"%@.caf",[dateFormat stringFromDate:[NSDate date]]];
//
return [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),recordPath]];
}
3. AVPlayerViewController
有x 有进度条 有静音
// 1.创建AVPlayerViewController
AVPlayerViewController *playC=[AVPlayerViewController new];
// 2.设置AVPlayer(视频路径)
[playC setPlayer:[AVPlayer playerWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"1.mp4" ofType:nil]]]];
// 3.弹出AVPlayerViewController(默认:不播放)
[self presentViewController:playC animated:true completion:^{
}];
// 4.1 播放
[playC.player play];
// 4.2 暂停
[playC.player pause];
// 4.3 一组视频
// AVQueuePlayer:AVPlayer(播放完毕后自动下一首)
AVPlayerItem *avItem=[AVPlayerItem playerItemWithURL:fileUrl];
AVPlayerItem *avTItem=[AVPlayerItem playerItemWithURL:fileUrl];
// 不能放2个同名的item,会崩
AVQueuePlayer *avPlayer=[AVQueuePlayer queuePlayerWithItems:@[avItem,avTItem]];
4. AVPlayer
只有界面,没有工具条(用于高度自定义 视频视图)
// 1.创建AVPlayer
AVPlayer *avPlayer=[AVPlayer playerWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"1.mp4" ofType:nil]]];
// 1.1添加观察(用于获取进度 更新进度条)
[avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
// 总时长
float allTime=CMTimeGetSeconds(avPlayer.currentItem.duration);
// 当前已播放时长
float currentTime=CMTimeGetSeconds(avPlayer.currentTime);
// 更新进度条
}];
// 2.创建显示视频的层(没有控制视图层,只有视频)
AVPlayerLayer *playLayer=[AVPlayerLayer playerLayerWithPlayer:avPlayer];
[playLayer setFrame:CGRectMake(0, 0, 200, 200)];
[self.view.layer addSublayer:playLayer];
// 设置 播放视频的位置
[avPlayer seekToTime:CMTimeMakeWithSeconds(CMTimeGetSeconds(avPlayer.currentItem.duration)*1/6, 1)];
// 添加通知---视频播放完毕
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(finishVideo) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
// 销毁通知
[[NSNotificationCenter defaultCenter]removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
AVPlayerViewController: UIViewController
// AVPlayer:负责播放视频
AVPlayer *player=playC.player;
// 是否显示控制视图(默认:true,设置为false后只有视频了,视频上的所有控制View都不显示)
[playC setShowsPlaybackControls:false];
// 设置视频的显示style
[playC setVideoGravity:AVLayerVideoGravityResizeAspectFill];
/*
AVLayerVideoGravityResizeAspect(默认)
AVLayerVideoGravityResizeAspectFill
AVLayerVideoGravityResize
*/
// 是否准备好播放视频(readOnly)
BOOL isReadyDisplay=[playC isReadyForDisplay];
// 显示视频View的bounds(readOnly)
CGRect videoBounds=playC.videoBounds;
// 覆盖层(位于视频层和控制层中间,用来添加自定义覆盖物)(readOnly)
UIView *overlayView=playC.contentOverlayView;
UIView *aV=[UIView new];
[aV setFrame:CGRectMake(0, 0, 200, 200)];
[aV setBackgroundColor:[UIColor blueColor]];
[overlayView addSubview:aV];
// 是否允许画中画?(默认:true)
[playC setAllowsPictureInPicturePlayback:false];
// 是否更新播放信息?(默认:true)
[playC setUpdatesNowPlayingInfoCenter:false];
// 点击播放按钮后是否全屏(默认:false)
[playC setEntersFullScreenWhenPlaybackBegins:true];
// 播放结束后是否离开全屏(默认:false)
[playC setExitsFullScreenWhenPlaybackEnds:true];
dele
[playC setDelegate:self]; // AVPlayerViewControllerDelegate
// 即将开始画中画时调用
-(void)playerViewControllerWillStartPictureInPicture:(AVPlayerViewController *)playerViewController{}
// 已经开始画中画时调用
-(void)playerViewControllerDidStartPictureInPicture:(AVPlayerViewController *)playerViewController{}
// 画中画开启失败后调用
-(void)playerViewController:(AVPlayerViewController *)playerViewController failedToStartPictureInPictureWithError:(NSError *)error{}
// 即将停止画中画时调用
-(void)playerViewControllerWillStopPictureInPicture:(AVPlayerViewController *)playerViewController{}
// 停止画中画后调用
-(void)playerViewControllerDidStopPictureInPicture:(AVPlayerViewController *)playerViewController{}
// 是否应该自动消失画中画
-(BOOL)playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart:(AVPlayerViewController *)playerViewController{ return true;}
// 重新恢复画中画后调用
-(void)playerViewController:(AVPlayerViewController *)playerViewController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL))completionHandler{}
AVPlayer
AVPlayer : NSObject
创建AVPlayer---4方式
AVPlayer *avPlayer=[AVPlayer playerWithURL:[NSURL URLWithString:@""]];
AVPlayer *avPlayer=[AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithURL:[NSURL URLWithString:@""]]];
AVPlayer *avPlayer=[[AVPlayer alloc]initWithURL:[NSURL URLWithString:@""]];
AVPlayer *avPlayer=[[AVPlayer alloc]initWithPlayerItem:[AVPlayerItem playerItemWithURL:[NSURL URLWithString:@""]]];
// status
AVPlayerStatus status=avPlayer.status;
/*
AVPlayerStatusUnknown 未知
AVPlayerStatusReadyToPlay 准备好播放
AVPlayerStatusFailed 失败
*/
// error
NSError *error=avPlayer.error;
AVPlayerItem
用于播放多个视频,代表单个视频
// 创建
AVPlayerItem *playItem=[AVPlayerItem playerItemWithURL:[NSURL URLWithString:@""]];
AVPlayerItem *playItem=[AVPlayerItem playerItemWithAsset:[AVAsset assetWithURL:[NSURL URLWithString:@""]]];
AVPlayerItem *playItem=[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:@""];
AVPlayerItem *playItem=[AVPlayerItem alloc]initWithAsset:[AVAsset assetWithURL:[NSURL URLWithString:@""]];
// 视频的状态(readOnly)
AVPlayerItemStatus itemStatus=playItem.status;
// error
NSError *error=playItem.error;