ios - 发布音频 - Cocoa Xcode(内存管理)

标签 ios xcode cocoa audio

所以在我之前的问题FOUND HERE ,每次我在我的 iOS 游戏中让我的 Sprite 跳跃时,我都试图找到播放“跳跃”声音的最佳方式......

今天出于某种原因,我开始担心我正在加载音频文件数百万次并浪费内存:(

任何人,已经向我建议了以下内容,(所以每次我通过点击屏幕跳跃时,都会加载并播放声音)......

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
    {
            //NSString *
            jumpSound = [[NSBundle mainBundle] pathForResource:@"boing" ofType:@"mp3"];

            //AVAudioPlayer *
            jumpAffect = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:jumpSound] error:NULL];

            [jumpAffect prepareToPlay];
            [jumpAffect play];

            //then, make sprite jump
            jumpUp = 16;
    }

上述方法允许我快速按下跳转并重新启动音频循环,即使前一个循环(来自上一个跳转)尚未完成。

值得记住的是,这可能每分钟发生数百次(或者更现实的是每秒发生几次)......

这是一个问题吗?完成方法/游戏循环后是否需要释放轨道?

最佳答案

我认为你的最后一个问题完全不正确。 AVAudioPlayer 对游戏有太多的延迟。当你跳跃时,声音可能会在一秒钟后发生,而不是在你想要的时候立即发生。如果您不想每分钟播放一百万次声音,您应该像这样使用 AudioServices:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
     NSURL *pathURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"boing" ofType:@"wav"]];

     SystemSoundID audioEffect;
     AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &audioEffect);
     AudioServicesPlaySystemSound(audioEffect);
     //then, make sprite jump
     jumpUp = 16;
}

您必须将您的 mp3 转换为 wav 或 caf。但我认为这个权衡是值得的......

关于ios - 发布音频 - Cocoa Xcode(内存管理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26290200/

相关文章:

objective-c - Mac OSX - 如何使用 Cocoa 甚至纯 C 函数获取代理配置?

cocoa - 通过 NSTask 执行时 tops 命令给出错误

ios - 将 Codable 结构编码为 JSON 后如何存储数据

iphone - 如何自动发送短信?

ios - UITableView 未正确提取 JSON

cocoa - 界面生成器错误: IBXMLDecoder: The value for key is too large to fit into a 32 bit integer

iOS 7 后台传输服务在 3 分钟后停止

ios - 使用构造函数来初始化实例变量子类 PFObject

ios - 更新 tableview 中的单元格同时更新另一个单元格

ios - 为什么语言更改需要在 Objective C 中重新启动应用程序