1.向項目中添加AVFoundation.framework
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0NXYFhGd192UvwVe0lmdhJ3ZvwFM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2LcZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39zNyYzN0MDM4ATMwETM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
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]; }