- (AVAudioPlayer *)loadMusic:(NSString *)fileName
{
// 找到指定文件的路径
NSString *path = [[NSBundle mainBundle]pathForResource:fileName ofType:nil];
// 将文件名转换为URL
NSURL *url = [NSURL fileURLWithPath:path];
// 初始化音频播放器
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
// 设置循环播放
[player setNumberOfLoops:-1];
// 设置声音大小,0.5f---50%
[player setVolume:0.5f];
// 准备声音
[player prepareToPlay];
return player;
}
AVAudioPlayer *_backgroundMusic;
// 初始化音乐播放器
_backgroundMusic = [self loadMusic:@"背景音乐.caf"];
// 开始播放
[_backgroundMusic play];
aiff格式
1.导入包:AudioToolbox.framework
2.
#pragma mark Sound
- (SystemSoundID)loadSound:(NSString *)fileName
{
// 指定文件路径
NSString *path = [[NSBundle mainBundle]pathForResource:fileName ofType:nil];
// 将文件名转换为URL格式
NSURL *url = [NSURL fileURLWithPath:path];
// 初始化音效
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);
return soundID;
}
SystemSoundID _winSound;
// 加载音效
_winSound = [self loadSound:@"胜利.aiff"];
// 播放音效
AudioServicesPlaySystemSound(_winSound);
// 当声音关闭的时候,提示时有震动
AudioServicesPlayAlertSound(_winSound);