2015-02-02 13 views
4

를 OpenAL의 재생을위한 다른 기술 대 AVAudioPlayer 대 소리 그러나 어떤 압축 오디오 포맷을 지원하지 않으며 사용하기 너무 쉬운 일이 아닙니다하지만 mp3와 같은 압축 형식뿐만 아니라 광범위한 파일 형식을 지원합니다.,</p> <p>AVAudioPlayer하지 너무 빨리입니다 ... 내가 OpenAL에 빠른 라이브러리는 것을 알고

또한 내가 몇 가지 질문이 SKAction의 사운드뿐만 아니라 SystemSoundID을 재생할 수 있습니다 클래스 ...

가 :

  1. 에 선호하는 방법/플레이어/기술 일 것입니다 무엇 재생 :

    • 효과음 (여러 번에)? 때때로 또한
  2. 루프

  3. 배경 음악 작은 시간 지연 후에 반복 될 수
  4. 음향 효과, 음향 효과를 위해 비 압축 오디오를 사용하는 현명한입니까? 나는 그 파일이 어쨌든 작은 크기를 가지고 있기 때문에 이것은 괜찮은가요?

답변

4

저는 개인적으로 ObjectAL을 사용하고 있습니다. OpenAL과 AVAudioPlayer를 사용하지만 복잡한 부분을 많이 추상화했기 때문에 좋습니다. 내 게임에는 배경 음악, 동시에 재생되는 수많은 톤 및 스프라이트 속도에 따라 음량, 음조 등이 증가하는 반복 가능한 사운드가 있습니다. ObjectAL은 그 모든 것을 할 수 있습니다.

ObjectAL은 OALSimpleAudio 클래스를 사용하여 간단한 사운드 및 음악 루프를 재생하는 데 사용할 수 있습니다. 또는 더 깊숙이 들어가서 더 복잡한 작업을 수행 할 수도 있습니다.

내 게임을 위해 특별히 ObjectAL 주변에 간단한 래퍼를 만들었으므로 더 멀리 추상화되었습니다.

내가 읽은 것부터 압축되지 않은 오디오가 더 좋습니다. 사운드를 재생할 때마다 파일을 당기지 않도록 게임을 미리로드해야합니다.

+0

이것은보기에 좋고 간단합니다. 시도해 보겠습니다. 하지만 예제에서 dealloc 메서드를 이해할 수 있는지 확신 할 수 없습니다. 왜 수동으로 release를 호출할까요? – Whirlwind

+0

예고편이 릴리스 전을 보았을 가능성이 높기 때문에이 예에서 릴리스가 발생했다고 생각합니다. 이것은 꽤 오래된 라이브러리입니다. 아마 릴리스를 사용하거나 보유 할 필요는 없습니다. – hamobi

+0

아, 이해합니다. 감사! – Whirlwind

3

이 매우 간단한 클래스는 동시에 많은 소리를 사용하여 완벽하게 여러 프로젝트를 처리했습니다. 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]; 
+0

답장을 보내 주셔서 감사합니다. 시험해 보겠습니다. 이 방법에 대해 들었지만 (GCD 소리가 들리지만) 실제로 구현 된 것은 본 적이 없습니다. – Whirlwind

2

다음은 @patri의 포트입니다. 스위프트 3에 대한 ck의 해결책.

import AVFoundation 

// MARK - 
// MARK setup sound 

// get a repeating sound 
func setupRepeatingSound(file: String, volume: Float) -> AVAudioPlayer? { 
    let sound: AVAudioPlayer? = setupSound(file: file, volume: volume) 
    sound?.numberOfLoops = -1 
    return sound 
} 

// setup a sound 
func setupSound(file: String, volume: Float) -> AVAudioPlayer? { 
    var sound: AVAudioPlayer? 
    if let path = Bundle.main.path(forResource: file, ofType:nil) { 
     let url = NSURL(fileURLWithPath: path) 
     do { 
      sound = try AVAudioPlayer(contentsOf: url as URL) 
     } catch { 
      // couldn't load file :(
     } 
    } 
    sound?.numberOfLoops = 0 
    sound?.volume = volume 
    sound?.prepareToPlay() 
    return sound 
} 

// MARK sound controls 

// play a sound now through GCD 
func playSound(_ sound: AVAudioPlayer?) { 
    if sound != nil { 
     DispatchQueue.global(qos: .default).async { 
      sound!.play() 
     } 
    } 
} 

// play a sound later through GCD 
func playSound(_ sound: AVAudioPlayer?, afterDelay: Float) { 
    if sound != nil { 
     DispatchQueue.main.asyncAfter(deadline: .now() + Double(afterDelay)) { 
      sound!.play() 
     } 
    } 
} 

// pause a currently running sound (mostly for background music) 
func pauseSound(_ sound: AVAudioPlayer?) { 
    sound?.pause() 
}