Playing sounds in iPhone SDK?

2019-03-13 18:04发布

Does anyone have a snippet that uses the 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!

3条回答
女痞
2楼-- · 2019-03-13 18:23

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);
查看更多
相关推荐>>
3楼-- · 2019-03-13 18:27

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.

查看更多
放我归山
4楼-- · 2019-03-13 18:41

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.

查看更多
登录 后发表回答