音频的播放

首先,需要导入AudioToolbox.framework库,然后在实现文件中引入进来:

 

#import <AudioToolbox/AudioToolbox.h>

 

接着,写一个播放声音的方法。

 

- (void)playSound{
	NSString *path = [[NSBundle mainBundle] pathForResource:@"win" 
                                                     ofType:@"wav"];
	SystemSoundID soundID;
	AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path]
									 , &soundID);
	AudioServicesPlaySystemSound (soundID);
}

 

当按钮按下时进行调用:

 

- (IBAction) btnPressed{
	[self performSelector:@selector(playSound) 
			   withObject:nil 
			   afterDelay:.5];
}

 

在播放之后,需要调用AudioServicesDisposeSystemSoundID方法释放SystemSoundID。因为AudioServicesPlaySystemSound是异步执行的,所以最佳的方法是当声音播放完的时候调用AudioServicesAddSystemSoundCompletion方法。

 

- (void)playSound{
	NSString *path = [[NSBundle mainBundle] pathForResource:@"win" 
                                                     ofType:@"wav"];
	SystemSoundID soundID;
	AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path]
									 , &soundID);
    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, &SoundFinished, NULL);
	AudioServicesPlaySystemSound (soundID);
}

- (void)SoundFinished(SystemSoundID snd, void* context){
    AudioServicesRemoveSystemSoundCompletion(snd);
    AudioServicesDisposeSystemSoundID(snd);
}

你可能感兴趣的:(音频的播放)