简体   繁体   English

如何在Xcode项目中添加声音效果?

[英]How to add sound effects to an Xcode project?

This is my code right now. 这是我的代码。 I am trying to add sound effects when a button is pressed. 我试图在按下按钮时添加声音效果。

#import <AudioToolbox/AudioToolbox.h>

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

}

and I am calling this on the function I want it to be executed (UIButton Action). 我在要执行它的函数上调用此函数(UIButton操作)。

AudioServicesPlaySystemSound(_threeExplosionsID);

Firstly, thats not how you should be calling your mp3 file, you should be using the av audio player object. 首先,那不是您应该如何调用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];

Make sure you have strong reference to it, otherwise it might get removed in memory 确保对它有严格的引用,否则它可能会在内存中被删除

@property (strong,nonatomic) AVAudioPlayer *audioPlayer;

I would check that the method is being called when the button is being pressed. 我将检查按下按钮时是否正在调用该方法。 If you have a touchupinside action, then your method will be: 如果您有一个touchupinside动作,那么您的方法将是:

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

If that is not working, you should check that the resource is being added to your project, in Xcode you need to make sure you have added it. 如果这不起作用,则应检查是否已将资源添加到项目中,需要确保已在Xcode中添加了该资源。

在此处输入图片说明

In my project i created a subfolder called resources and then an additional one called sounds and placed it neatly in there. 在我的项目中,我创建了一个名为资源的子文件夹,然后又创建了一个名为声音的子文件夹,并将其整齐地放置在其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM