播放自定义音效 - (Obj-C)

音效: 相对音乐比较短,30s以内,不能控制播放(暂停),30s以上是不能通过音效播放的

需要使用<AVFoundation/AVFoundation.h>框架

音效通常用于提示音,往往需要多次使用,多次使用一般会使用缓存处理

创建音效需要设置一个soundID标识符,通过soundID操作对应的音效

示例代码:

#import "ViewController.h"

// 导入头文件
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()
// 音效缓存
@property (nonatomic,strong) NSMutableDictionary *soundIdCache;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self playSystemSoundWithFileName:@"buyao.caf"];
}


- (void)playSystemSoundWithFileName:(NSString *)fileName{
    
    // AudioServicesPlayAlertSound(<#SystemSoundID inSystemSoundID#>)  手机设置静音时会震动
    
    // 设置自定义声音文件的路径
    NSString *filePath = [[NSBundle mainBundle]pathForResource:fileName ofType:nil];
    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
    
    // 从缓存中获取
    SystemSoundID soundID = [[self.soundIdCache objectForKey:fileName] unsignedIntValue];
    // 判断是否存在
    if (soundID == 0) {
        
        // 生成soundID 音效的唯一标识符  (防止每次都去生成(经常使用),消耗性能,所以使用缓存记录)
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(fileUrl), &soundID);
        
        // 添加到缓存中
        [self.soundIdCache setObject:@(soundID) forKey:fileName];
        NSLog(@"添加到缓存");
    }
    
    // AudioServicesPlaySystemSound 播放系统音效
    AudioServicesPlaySystemSound(soundID);
    
}

// 内存紧张时调用
- (void)didReceiveMemoryWarning{
    
    for (NSNumber *soundIDNumber in self.soundIdCache.allValues) {
        // 销毁内存中的音效
        AudioServicesRemoveSystemSoundCompletion(soundIDNumber.unsignedIntValue);
        NSLog(@"删除内存中的音效");
    }
    // 移除缓存中存放的ID
    // [self.soundIdCache removeAllObjects]; soundIdCache还存在,只清除了内部存放的内容
    self.soundIdCache = nil;
    NSLog(@"清除缓存");
    
}

#pragma mark - 缓存懒加载
- (NSMutableDictionary *)soundIdCache{
    
    if (_soundIdCache == nil) {
        _soundIdCache = [NSMutableDictionary dictionary];
        NSLog(@"生成缓存");
    }
    return _soundIdCache;
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容