如何向Xcode项目添加音效?

3

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

#import <AudioToolbox/AudioToolbox.h>

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

}

我正在调用这个函数以使其执行(UIButton Action)。

AudioServicesPlaySystemSound(_threeExplosionsID);

3
可能是如何在iOS中给按钮添加声音?的重复问题。 - Teja Nandamuri
1个回答

5
首先,您不应该这样称呼您的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操作,那么您的方法将是:
-(IBAction)buttonPressed {
    [self threeBombExplosion];
}

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

enter image description here

在我的项目中,我创建了一个名为“资源”的子文件夹,然后又创建了一个名为“声音”的附加文件夹,并将其整齐地放置在其中。

不确定“你应该使用AV音频播放器”,Audio Services系统声音非常适合像这样简单的用途。 - jcaron
他试图播放的声音不是系统声音,而是游戏声音。 - Reedy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接