开发者

Playing sounds in iPhone SDK?

Does anyone have a snippet that uses t开发者_如何学Gohe AudioToolBox framework that can be used to play a short sound? I would be grateful if you shared it with me and the rest of the community. Everywhere else I have looked doesn't seem to be too clear with their code.

Thanks!


Here is an easy example using the AVAudioPlayer:

-(void)PlayClick
{
    NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                               pathForResource:@"click"
                                               ofType:@"caf"]];
    AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
    [click play];
    [click release];
}

This assumes a file called "click.caf" available in the main bundle. As I play this sound a lot, I actually keep it around to play it later instead of releasing it.


I wrote a simple Objective-C wrapper around AudioServicesPlaySystemSound and friends:

#import <AudioToolbox/AudioToolbox.h>

/*
    Trivial wrapper around system sound as provided
    by Audio Services. Don’t forget to add the Audio
    Toolbox framework.
*/

@interface Sound : NSObject
{
    SystemSoundID handle;
}

// Path is relative to the resources dir.
- (id) initWithPath: (NSString*) path;
- (void) play;

@end

@implementation Sound

- (id) initWithPath: (NSString*) path
{
    [super init];
    NSString *resourceDir = [[NSBundle mainBundle] resourcePath];
    NSString *fullPath = [resourceDir stringByAppendingPathComponent:path];
    NSURL *url = [NSURL fileURLWithPath:fullPath];

    OSStatus errcode = AudioServicesCreateSystemSoundID((CFURLRef) url, &handle);
    NSAssert1(errcode == 0, @"Failed to load sound: %@", path);
    return self;
}

- (void) dealloc
{
    AudioServicesDisposeSystemSoundID(handle);
    [super dealloc];
}

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

@end

Lives here. For other sound options see this question.


Source: AudioServices - iPhone Developer Wiki

The AudioService sounds are irrespective of the the device volume controller. Even if the phone is in silent mode the Audio service sounds will be played. These sounds can only be muted by going Settings -> Sounds -> Ringer and Alerts.

Custom system sounds can be played by the following code:

CFBundleRef mainbundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef = CFBundleCopyResourceURL(mainbundle, CFSTR("tap"), CFSTR("aif"), NULL);
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundFileObject);

Invoking the vibration in iPhone

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

Playing inbuilt system sounds.

AudioServicesPlaySystemSound(1100);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜