1. System Sound Services
System Sound Services 是最底层也是最简单的声音播放服务,调用 AudioServicesPlaySystemSound 这个方法就可以播放一些简单的音频文件,使用此方法只适合播放一些很小的提示或者警告音,因为它有很多限制:
声音长度要小于 30 秒
代码展现:
路径
NSString *path = [[NSBundle mainBundle]pathForResource:@"duanxin2.caf" ofType:nil];
NSLog(@"%@",path);
NSURL *url = [NSURL fileURLWithPath:path];
SystemSoundID soundID = 0;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID );
AudioServicesPlayAlertSound(soundID);
2. AVAudioPlayer 类
AVAudioPlayer 是 AVFoundation.framework 中定义的一个类,所以使用要先在工程中引入 AVFoundation.framework。我们可以把 AVAudioPlayer 看作是一个高级的播放器,
可播放 MP3等多种格式
AVAudioPlayer 可以播放任意长度的音频文件、支持循环播放、可以同步播放多个音频文件、控制播放进度以及从音频文件的任意一点开始播放等,更高级的功能可以参考 AVAudioPlayer 的文档 。要使用 AVAudioPlayer 的对象播放文件,你只需为其指定一个音频文件并设定一个实现了 AVAudioPlayerDelegate 协议的 delegate 对象。
只要将 AVAudioPlayer 的 numberOfLoops 属性设为负数,音频文件就会一直循环播放直到调用 stop 方法。
NSString *musicPath = [[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"%@",y音乐名.格式] ofType:nil];
// NSURL *url = [NSURL fileURLWithPath:musicPath];
// _player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
// _player.numberOfLoops=0;//小于零无限循环,零是不循环,1是循环1次.....
// _player.volume=1;//音量
// [_player prepareToPlay];//加入缓存区
最后,[ _player play];