Cocos2d-音乐播放(音效循环播放&&停止)
//预加载背景音乐 和 预加载音效 在播放背景音乐与音效之前都要提前加载,为了防止加载消耗时间发生与游戏不同步;
[[SimpleAudioEngine sharedEngine] preloadBackgroundMusic:@"office_background.mp3"];
[[SimpleAudioEngine sharedEngine] preloadEffect:@"office_background.mp3"];
//播放背景音乐 和 循环播放背景音乐;
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"office_background.mp3"];
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"school_kissing.mp3" loop:YES];
//暂停播放背景音乐;
[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];
//继续播放背景音乐(不是从头开始播)
[[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];
//停止播放背景音乐
[[SimpleAudioEngine sharedEngine] stopBackgroundMusic];
//设置背景音乐音量大小;
[CDAudioManager sharedManager].backgroundMusic.volume=1.0; //(volume值范围为0.0-1.0);
//背景音乐播放几次:
[CDAudioManager sharedManager].backgroundMusic.numberOfLoops= int值;
//背景音乐播放完后:
[[CDAudioManager sharedManager] setBackgroundMusicCompletionListener:self selector:@selector(触发的方法)];
//播放音效;
[[SimpleAudioEngine sharedEngine] playEffect:@"school_kissing.mp3"];
//pitch(值范围:>0){值最大,音调越高,播放时间越短} pan:(值范围:-1到1)貌似是左右声道 gain:(值范围:>0)音量大小;
[[SimpleAudioEngine sharedEngine] playEffect:@"office_background.mp3" pitch:3.0 pan:-1 gain:0.1];
有时我们需要循环播放一个音效;
可以做如下操作:
在 #import "SimpleAudioEngine.h" 源码中:
-(ALuint) playEffect:(NSString*) filePath loop:(BOOL)loop;
-(ALuint) playEffect:(NSString*) filePath pitch:(Float32) pitch pan:(Float32) pan gain:(Float32) gain loop:(BOOL)loop;
在 #import "SimpleAudioEngine.m"源码中 实现方法:
-(ALuint) playEffect:(NSString*) filePath loop:(BOOL)loop
{
return [self playEffect:filePath pitch:1.0f pan:0.0f gain:1.0f loop:loop];
}
-(ALuint) playEffect:(NSString*) filePath pitch:(Float32) pitch pan:(Float32) pan gain:(Float32) gain loop:(BOOL)loop
{
int soundId = [bufferManager bufferForFile:filePath create:YES];
if (soundId != kCDNoBuffer) {
return [soundEngine playSound:soundId sourceGroupId:0 pitch:pitch pan:pan gain:gain loop:loop];
} else {
return CD_MUTE;
}
}
这样我们就可以用如下方法实现音效循环播放:
//loop循环播放音效;
[[SimpleAudioEngine sharedEngine] playEffect:@"school_kissing.mp3" loop:YES];
[[SimpleAudioEngine sharedEngine] playEffect:@"school_kissing.mp3" pitch:1.0 pan:0.0 gain:1.0 loop:YES];
停止播放音效:设一个全局的静态变量:
static int i=1;(随便赋个值)
在播放音效时候 i=[[SimpleAudioEngine sharedEngine] playEffect:@"school_kissing.mp3" loop:YES];
停止播放音效: [[SimpleAudioEngine sharedEngine] stopEffect:i];
需要注意的是:如有多个音效播放,索引值不能是同一个, 因为每次播放都会返回一个int值如:
i=[[SimpleAudioEngine sharedEngine] playEffect:@"abc.mp3" loop:YES]; i=[[SimpleAudioEngine sharedEngine] playEffect:@"def.mp3" loop:YES];
[[SimpleAudioEnginesharedEngine] stopEffect:i];
//播放abc可能返回值为100,播放def返回为101,这样通过同一个索引“i”就不能停止abc的播放了;
你会发现,还在循环播放;必须使用不同的“索引”才行;