添加音频(2种:背景音乐与音效)
1.添加背景音乐
引入库
在需要使用的视图中添加协议
创建 AVAudioPlayer 对象 声明
创建button控件,委托
实现开始音乐方法
-(void)startPlayer
{
//定义URL
NSBundle获取文件路径
NSURL *audioPath=[[NSURL alloc]initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"音乐名" ofType:@"扩展名"]];
NSError *error=nil;
//audioPlayer初始化
audioplayer=[[AVAudioPlayer alloc]initWithContentsOfURL:audioPath error:&error];
//设置代理
audioplayer.delegate=self;
//判断是否错误
if(error!=nil)
{
NSLog(@"播放遇到错误了 信息:%@",[error description]);
return ;
}
//开始播放
[audioplayer play];
}
停止播放方法
-(void)stopPlayer
{
[audioplayer stop];
}
------------------------------------------------------------
2.添加音效
同种音效,可以同事并存,进行叠加
引入库
-(void)startPlayer
{
//定义URL
NSURL *voicePath=[[NSURL alloc]initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"gameover_bg_over" ofType:@"wav"]];
//定义音效对象
SystemSoundID soundID;
//注册服务(地址,对象)
AudioServicesCreateSyste
mSoundID((__bridge CFURLRef)voicePath , &soundID);
//添加回调方法(soundID执行完,回调方法playFinish(自己定义))
AudioServicesAddSystemSo
undCompletion(soundID, NULL, NULL,playFinish , NULL);
//开始播放
AudioServicesPlayAlertSo
und(soundID);
}
-------------------------------------------------------------
添加视频
引入库
定义一个播放器的类
MPMoviePlayerViewControl
ler *videoPlayer;
//开始播放视频
-(void)startPlayer
{
//获取视频文件路径
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"mtv" ofType:@"3gp"];
//加载URL
NSURL *videoUrl = [NSURL fileURLWithPath:filePath];
//初始化播放器并且设定播放模式
videoPlayer = [[MPMoviePlayerViewControl
ler alloc] initWithContentURL:videoUrl];
//控制模式(触摸)
videoPlayer.moviePlayer.scalingMode = MPMovieScalingModeAspect
Fill;
//设定播放模式
videoPlayer.moviePlayer.controlStyle = MPMovieControlStyleFulls
creen;
//开始播放
[[[UIApplication sharedApplication] keyWindow] addSubview:videoPlayer.view];
}
- (void)dealloc
{
//移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
//释放资源
[videoPlayer release];
[super dealloc];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//初始化通知
//为什么要加通知?
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDone) name:MPMoviePlayerPlaybackDid
FinishNotification object:nil];
}
//视频播放完成的通知方法
-(void)playerDone
{
NSLog(@"视频播放完成!");
[videoPlayer.view removeFromSuperview];
[videoPlayer release];
videoPlayer = nil;
}