2012-03-20 40 views

回答

25

這是打一個簡單的聲音在iOS中(不超過30秒)的最佳方式:

//Retrieve audio file 
NSString *path = [[NSBundle mainBundle] pathForResource:@"soundeffect" ofType:@"m4a"]; 
NSURL *pathURL = [NSURL fileURLWithPath : path]; 

SystemSoundID audioEffect; 
AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect); 
AudioServicesPlaySystemSound(audioEffect); 

// call the following function when the sound is no longer used 
// (must be done AFTER the sound is done playing) 
AudioServicesDisposeSystemSoundID(audioEffect); 
+0

我只是做這個自己。 – 2012-03-20 21:18:29

+0

謝謝!有效! – noloman 2013-08-22 10:15:27

+0

謝謝兄弟!其作品.. – 2015-01-05 05:54:51

29

我用這個:

頭文件:

#import <AudioToolbox/AudioServices.h> 

@interface SoundEffect : NSObject 
{ 
    SystemSoundID soundID; 
} 

- (id)initWithSoundNamed:(NSString *)filename; 
- (void)play; 

@end 

源文件:

#import "SoundEffect.h" 

@implementation SoundEffect 

- (id)initWithSoundNamed:(NSString *)filename 
{ 
    if ((self = [super init])) 
    { 
     NSURL *fileURL = [[NSBundle mainBundle] URLForResource:filename withExtension:nil]; 
     if (fileURL != nil) 
     { 
      SystemSoundID theSoundID; 
      OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileURL, &theSoundID); 
      if (error == kAudioServicesNoError) 
       soundID = theSoundID; 
     } 
    } 
    return self; 
} 

- (void)dealloc 
{ 
    AudioServicesDisposeSystemSoundID(soundID); 
} 

- (void)play 
{ 
    AudioServicesPlaySystemSound(soundID); 
} 

@end 

您將需要創建一個SoundEffect實例並直接調用該方法。

+0

這太好了。我使用的是SystemSoundID的C數組,但是我只是碰到了schlepp需要處理的一點。切換到基於此的東西。謝謝! – 2012-10-19 23:46:42

+2

雖然這不適用於ARC。爲了在ARC中使用它,你必須添加一個完成回調函數,你可以在這裏處理systemsound。如果你在dealloc中這樣做,聲音立即死亡: 'AudioServicesAddSystemSoundCompletion(soundID,NULL,NULL,completionCallback,(__bridge_retained void *)self);' 像這樣的例子 – Maverick1st 2013-04-08 15:07:32

+0

@ Maverick1st這與ARC非常吻合,必須確保你的'SoundEffect'對象不會立即被釋放,比如將它分配給一個屬性。 – shawkinaw 2013-07-26 22:15:03

10

(小修改正確的答案照顧音頻的處置)

NSString *path = [[NSBundle mainBundle] pathForResource:@"soundeffect" ofType:@"m4a"]; 
NSURL *pathURL = [NSURL fileURLWithPath : path]; 

SystemSoundID audioEffect; 
AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect); 
AudioServicesPlaySystemSound(audioEffect); 
// Using GCD, we can use a block to dispose of the audio effect without using a NSTimer or something else to figure out when it'll be finished playing. 
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
    AudioServicesDisposeSystemSoundID(audioEffect); 
}); 
+1

這是異步播放聲音的最佳方式。 – alones 2014-12-11 02:19:46

相關問題