How to implement sound into an existent app, witho

2020-07-18 02:16发布

问题:

For example, on the iOS SDK download page, there's sample code; I'm using the calculator app (iPhoneUnitTests). I would like to know if it is possible to add sounds to the button presses on the app that's already built, easily.

回答1:

It is actually very simple to play short sounds, like button sounds. Here is a quick example.

You must link the AudioToolbox.framework binary

SoundExampleViewController.h;

#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
@interface SoundExampleViewController : UIViewController{
    SystemSoundID mySoundID;
}
@end

SoundExampleViewController.m:

#import "SoundExampleViewController.h"
@implementation SoundExampleViewController
- (void)viewDidLoad{
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"SoundFileName" ofType:@"wav"]; 
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&mySoundID);
}
- (void)viewDidUnload{
    [super viewDidUnload];
    AudioServicesDisposeSystemSoundID(mySoundID);
}
@end

Then to play you simply call: AudioServicesPlaySystemSound(mySoundID);