博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
音乐和音效的加载播放
阅读量:4694 次
发布时间:2019-06-09

本文共 1317 字,大约阅读时间需要 4 分钟。

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

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 = -1;    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);

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

转载于:https://www.cnblogs.com/litaowei/p/3719248.html

你可能感兴趣的文章
(转)Maven仓库——私服介绍
查看>>
设计模式之工厂模式
查看>>
仿复制粘贴功能,长按弹出tips的实现
查看>>
Kubernetes-Host网络模式应用
查看>>
第三次作业
查看>>
使用HTML5构建iOS原生APP(2)
查看>>
sqlplus terminators - Semicolumn (;), slash (/) and a blank line
查看>>
省选知识清单/计划列表(咕?)
查看>>
远程桌面(3389)复制(拖动)文件
查看>>
转 lucene3搜索引擎,索引建立搜索排序分页高亮显示, IKAnalyzer分词
查看>>
bootstrap datetimepicker 位置错误
查看>>
9结构型模式之代理模式
查看>>
第二节 整型数据
查看>>
Python 序列
查看>>
Liferay的架构:缓存(第一部分)
查看>>
初识B/S结构编程技术
查看>>
方法、hadoop源码之JobQueueTaskScheduler-by小雨
查看>>
页面重构总结
查看>>
IO 函数
查看>>
Unity V3 初步使用 —— 为我的.NET项目从简单三层架构转到IOC做准备
查看>>