이 매우 간단한 클래스는 동시에 많은 소리를 사용하여 완벽하게 여러 프로젝트를 처리했습니다. OpenAL을 사용하는 것보다 훨씬 간단하다는 것을 알았습니다. 그것은 당신이 요구 한 모든 것을 가지고 있으며, 사전 설정 사운드, 다중 동시 재생, 지연 후, 백그라운드 루프.
먼저 압축 파일을 설정했기 때문에 압축 파일을 사용하는지 여부는 중요하지 않습니다.
SKAudio.h
#import <Foundation/Foundation.h>
@import AVFoundation;
@interface SKAudio : NSObject
+(AVAudioPlayer*)setupRepeatingSound:(NSString*)file volume:(float)volume;
+(AVAudioPlayer*)setupSound:(NSString*)file volume:(float)volume;
+(void)playSound:(AVAudioPlayer*)player;
+(void)playSound:(AVAudioPlayer*)player afterDelay:(float)delaySeconds;
+(void)pauseSound:(AVAudioPlayer*)player;
@end
SKAudio.m는
#import "SKAudio.h"
@implementation SKAudio
#pragma mark -
#pragma mark setup sound
// get a repeating sound
+(AVAudioPlayer*)setupRepeatingSound:(NSString*)file volume:(float)volume {
AVAudioPlayer *s = [self setupSound:file volume:volume];
s.numberOfLoops = -1;
return s;
}
// setup a sound
+(AVAudioPlayer*)setupSound:(NSString*)file volume:(float)volume{
NSError *error;
NSURL *url = [[NSBundle mainBundle] URLForResource:file withExtension:nil];
AVAudioPlayer *s = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
s.numberOfLoops = 0;
s.volume = volume;
[s prepareToPlay];
return s;
}
#pragma mark sound controls
// play a sound now through GCD
+(void)playSound:(AVAudioPlayer*)player {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[player play];
});
}
// play a sound later through GCD
+(void)playSound:(AVAudioPlayer*)player afterDelay:(float)delaySeconds {
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delaySeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[player play];
});
}
// pause a currently running sound (mostly for background music)
+(void)pauseSound:(AVAudioPlayer*)player {
[player pause];
}
@end
은 게임에서 사용하려면
설정 클래스 변수 및 사전로드 사운드와 함께 :
static AVAudioPlayer *whooshHit;
static AVAudioPlayer *bgMusic;
+(void)preloadShared {
// cache all the sounds in this class
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
whooshHit = [SKAudio setupSound:@"whoosh-hit-chime-1.mp3" volume:1.0];
// setup background sound with a lower volume
bgMusic = [SKAudio setupRepeatingSound:@"background.mp3" volume:0.3];
});
}
...
// whoosh with delay
[SKAudio playSound:whooshHit afterDelay:1.0];
...
// whoosh and shrink SKAction
SKAction *whooshAndShrink = [SKAction group:@[
[SKAction runBlock:^{ [SKAudio playStarSound:whooshHit afterDelay:1.0]; }],
[SKAction scaleTo:0 duration:1.0]]];
...
[SKAudio playSound:bgMusic];
...
[SKAudio pauseSound:bgMusic];
이것은보기에 좋고 간단합니다. 시도해 보겠습니다. 하지만 예제에서 dealloc 메서드를 이해할 수 있는지 확신 할 수 없습니다. 왜 수동으로 release를 호출할까요? – Whirlwind
예고편이 릴리스 전을 보았을 가능성이 높기 때문에이 예에서 릴리스가 발생했다고 생각합니다. 이것은 꽤 오래된 라이브러리입니다. 아마 릴리스를 사용하거나 보유 할 필요는 없습니다. – hamobi
아, 이해합니다. 감사! – Whirlwind