AVFoundation 爲 UIButton 添加音效

1.向項目中添加AVFoundation.framework


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];
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章