Bogdan Vitoc
Bogdan Vitoc

Reputation: 139

How to Play a Sound Effect with AudioServices - Objective C

I have been searching the web for a way to play sounds in Objective C and I have found plenty of answers. However, when I try to play something three "Apple Mach-O Linker Errors" pop up.

Here is my code:

viewController.m

-(IBAction)shoot{
    tempSound *sound = [[tempSound alloc]init];
    [sound playSound:@"test" :@"wav"]  
}

tempSound.h

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

@interface tempSound : NSObject{
    SystemSoundID audioEffect;
}

-(void)playSound: (NSString*) fName : (NSString*) ext;

@end

tempSound.m

@implementation tempSound

-(void)playSound:(NSString *)fName :(NSString *)ext
{
    NSString *path  = [[NSBundle mainBundle] pathForResource : fName ofType :ext];

    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {

        NSURL *pathURL = [NSURL fileURLWithPath:path];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)pathURL, &audioEffect);
        AudioServicesPlaySystemSound(audioEffect);
    }

    else{
        NSLog(@"Error, file not found: %@",path);
    }


}

@end

Thanks in advance!

Upvotes: 1

Views: 1071

Answers (1)

user529758
user529758

Reputation:

You have to link against the AudioToolbox framework. (If you're using Xcode, you can add that in the "link with binaries" tab on the "build phases" section; if you're using a command line toolchain, you should add the -framework AudioToolbox linker flag.)

Upvotes: 5

Related Questions