首页 技术 正文
技术 2022年11月6日
0 收藏 735 点赞 1,086 浏览 1176 个字

在有些应用中需要用到背景音乐和音效,那在程序中是这么实现的。

1.首先加载背景音乐需要用到AVFoundation框架

2.音乐资源都是在包里的,所以需要获得包路径,涉及方法- (id)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError;

url其实就是包地址,可以通过[[NSBundlemainBundle]pathForResource:@”背景音乐” ofType:@”caf”];获得到路径path,然后用NSURL的fileURLWithPath方法将path转化为url;

3.设置音乐播放次数.numberOfLoops。设为0仅播放一次;设为1则循环1次播放2次;设为-1则循环播放不间断;

4.设置音乐声音大小.volume。

5.准备播放,调用方法 prepareToPlay。

6.开始播放,调用方法 play;停止播放:stop;

 NSString *path = [[NSBundle mainBundle]pathForResource:@"背景音乐" ofType:@"caf"];
NSURL *url = [NSURL fileURLWithPath:path];
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
player.numberOfLoops = -;
player.volume = 0.5f;
[player prepareToPlay];
[player play];

而加载音效则需要用到AudioToolbox框架,和音乐一样需要加载包路径,使用的方法是AudioServicesCreateSystemSoundID,这是个c语言的方法,其中传入的url需要用到__bridge进行转换,传出一个SystemSoundID来提供播放的时候调用,播放使用的方法是AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID) 。

 NSString *path = [[NSBundle mainBundle]pathForResource:soundFileName ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID); AudioServicesPlaySystemSound(soundID);<br>

此外还有个方法是AudioServicesPlayAlertSound,此方法在播放音效的同时会发出震动,给用户提醒。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,154
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,623
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,466
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,239
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,874
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,042