AVFoundation- 播放音效的例子

来源:互联网 发布:bt种子下载器for mac 编辑:程序博客网 时间:2024/06/10 23:26

0、获取inSystemSoundID,并播放音效
使用AudioServicesCreateSystemSoundID加载音效。

** 使用全局的静态变量存储ID,保证只加载一次资源*/+ (SystemSoundID)systemSoundIDWithFileName:(NSString *)fileName{    SystemSoundID inSystemSoundID = [_inSystemSoundIDs[fileName] unsignedIntValue];    if (inSystemSoundID ) {        return inSystemSoundID;    }    CFURLRef inFileURL = (__bridge CFURLRef)([[NSBundle mainBundle] URLForResource:fileName withExtension:nil]);    if (inFileURL == nil) {        return 0;    }    //加载音效    AudioServicesCreateSystemSoundID( inFileURL , &inSystemSoundID);    //播放音效(本地)    [_inSystemSoundIDs setObject:[NSNumber numberWithInt:inSystemSoundID] forKey:fileName];    return inSystemSoundID;}

1、使用AudioServicesPlaySystemSound 进行播放音频

2、/* 销毁soundID/
通过AudioServicesDisposeSystemSoundID 销毁soundID。并从字典数组移除。

+(void)audioServicesDisposeWithFileName:(NSString *)fileName{    if (fileName == nil) {        return;    }    SystemSoundID inSystemSoundID = [_inSystemSoundIDs[fileName] unsignedIntValue];    if (!inSystemSoundID ) {        return ;    }    AudioServicesDisposeSystemSoundID(inSystemSoundID);    //移除soundID    [_inSystemSoundIDs removeObjectForKey:fileName];}

常见问题

[_UIRemoteKeyboards proxy]_block_invoke Failed to access remote service: Error Domain=NSCocoaErrorDomain Code=4097 “connection to service named com.apple.UIKit.KeyboardManagement.hosted” UserInfo={NSDebugDescription=connection to service named com.apple.UIKit.KeyboardManagement.hosted}

这里写图片描述