天天看點

AVFoundation 為 UIButton 添加音效

1.向項目中添加AVFoundation.framework

AVFoundation 為 UIButton 添加音效

2.向目标檔案中添加方法:

- (void) playCoinSound {      //建立SystemSoundID對象,用于綁定聲音檔案     SystemSoundID soundFileObj;      //擷取聲音檔案的路徑     NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"CoinSound" ofType:@"mp3"];      //将string轉為url     NSURL *sourceUrl = [NSURL fileURLWithPath:sourcePath];      //将聲音檔案和SystemSoundID綁定     AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(sourceUrl), &soundFileObj);      //播放聲音,但此方法隻能播放30s以内的檔案     AudioServicesPlaySystemSound(soundFileObj); }

3.在UIButton動作方法中調用上面的方法:

- (IBAction)editButtonClick:(id)sender {      [self playCoinSound]; } 4.如果很多地方都設定按鈕聲音,可以為UIButton添加子類或分類,并在其中複寫 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event方法:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{      [self playCoinSound];

     [super touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event]; }