ios - 如何为 Xcode 项目添加音效?

标签 ios xcode resources

这是我现在的代码。 我正在尝试在按下按钮时添加音效。

#import <AudioToolbox/AudioToolbox.h>

- (void)threeBombExplosion
{
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"3Explosions" ofType:@"mp3"];
    NSURL *threeExplosionsURL = [NSURL fileURLWithPath:soundPath];
    AudioServicesCreateSystemSoundID(CFBridgingRetain(threeExplosionsURL),&_threeExplosionsID);

}

我在我希望它执行的函数(UIButton 操作)上调用它。

AudioServicesPlaySystemSound(_threeExplosionsID);

最佳答案

首先,您不应该这样调用您的 mp3 文件,您应该使用 av 音频播放器对象。

NSString *path = [[NSBundle mainBundle] pathForResource:@"3Explosions" ofType:@"mp3"];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
// Create audio player object and initialize with URL to sound
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];

确保你对它有强引用,否则它可能会在内存中被删除

@property (strong,nonatomic) AVAudioPlayer *audioPlayer;

我会检查按下按钮时是否正在调用该方法。 如果你有 touchupinside Action ,那么你的方法将是:

-(IBAction)buttonPressed {
    [self threeBombExplosion];
}

如果这不起作用,您应该检查资源是否已添加到您的项目中,在 Xcode 中您需要确保已添加它。

enter image description here

在我的项目中,我创建了一个名为 resources 的子文件夹,然后又创建了一个名为 sounds 的子文件夹,并将其整齐地放置在那里。

关于ios - 如何为 Xcode 项目添加音效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34402169/

相关文章:

ios - 如何杀死 Vapor 服务器

ios - UIScrollView 内的 Swift-Xcode UILabel

ios - 调试为什么 SKScene init(fileNamed :) returns nil

iphone - iOS : date problem

java - 收集对 JDBC 对象的引用并在循环中关闭它们是否安全?

ios - 如何每 10 秒使用 CLLocationManager 获取位置?

ios - 自定义 View 不通过在 Storyboard中添加 UIView 来继承自定义类来显示

c# - 如何检索嵌入式 xml 资源?

ios - APNS 更改通知消息

android - 在Android中访问错误的原始资源