SGSoundEffect.m 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // SGSoundEffect.m
  3. // SGQRCodeExample
  4. //
  5. // Created by kingsic on 2022/7/8.
  6. // Copyright © 2022 kingsic. All rights reserved.
  7. //
  8. #import "SGSoundEffect.h"
  9. #import <AudioToolbox/AudioServices.h>
  10. @interface SGSoundEffect ()
  11. {
  12. SystemSoundID _soundID;
  13. }
  14. @end
  15. @implementation SGSoundEffect
  16. - (id)initWithFilepath:(NSString *)path {
  17. self = [super init];
  18. if (self != nil) {
  19. // 获取声音文件路径
  20. NSURL *aFileURL = [NSURL fileURLWithPath:path isDirectory:NO];
  21. // 判断声音文件是否存在
  22. if (aFileURL != nil) {
  23. // 定义SystemSoundID
  24. SystemSoundID aSoundID;
  25. // 允许应用程序指定由系统声音服务器播放的音频文件
  26. /*
  27. 参数1:A CFURLRef for an AudioFile ,一个CFURLRef类型的音频文件
  28. 参数2:Returns a SystemSoundID,返回一个SystemSoundID
  29. */
  30. OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)aFileURL, &aSoundID);
  31. // 判断 error 是否等于无错误!
  32. if (error == kAudioServicesNoError) {
  33. // 赋值:
  34. _soundID = aSoundID;
  35. } else {
  36. NSLog(@"Error :loading sound path, %d, %@", (int)error, path);
  37. self = nil;
  38. }
  39. } else {
  40. NSLog(@"URL is nil for path %@", path);
  41. self = nil;
  42. }
  43. }
  44. return self;
  45. }
  46. + (id)soundEffectWithFilepath:(NSString *)path {
  47. if (path) {
  48. return [[SGSoundEffect alloc] initWithFilepath:path];
  49. }
  50. return nil;
  51. }
  52. - (void)play {
  53. AudioServicesPlaySystemSound(_soundID);
  54. }
  55. - (void)dealloc {
  56. AudioServicesDisposeSystemSoundID(_soundID);
  57. }
  58. @end