1、背景音乐播放 循环播放长音乐 支持mp3格式
#import <AVFoundation/AVFoundation.h>;
1 NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"changan" ofType:@"mp3"]; //创建音乐文件路径 2 NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath]; 3 4 AVAudioPlayer *thePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil]; 5 6 //创建播放器 7 self.myBackMusic = thePlayer; //赋值给自己定义的类变量 8 9 [musicURL release]; 10 [thePlayer release]; 11 12 [myBackMusic prepareToPlay]; 13 [myBackMusic setVolume:1]; //设置音量大小 14 myBackMusic.numberOfLoops = -1;//设置音乐播放次数 -1为一直循环 15 [myBackMusic play]; //播放
2、音效播放 短声音
#import <AudioToolbox/AudioToolbox.h>
NSString *thesoundFilePath = [[NSBundle mainBundle] pathForResource:@"Clapping Crowd Studio 01" ofType:@"caf"]; //创建音乐文件路径 CFURLRef thesoundURL = (CFURLRef) [NSURL fileURLWithPath:thesoundFilePath]; AudioServicesCreateSystemSoundID(thesoundURL, &sameViewSoundID); //变量SoundID与URL对应 AudioServicesPlaySystemSound(sameViewSoundID); //播放SoundID声音