Question

I have two classes one where I am initializing the SystemSoundID and then in a method that links to the actual sound file. But when I call the methods in my MainViewController and play it via IBAction, no sound plays.

Sound.h:

    #import <Foundation/Foundation.h>
    #import <AudioToolbox/AudioServices.h>

    @interface TheSound : NSObject {
        SystemSoundID yayFileID;
    }
    @property(nonatomic) SystemSoundID yayFileID;
    - (void) initSound;

    @end

Sound.m:

    #import "TheSound.h"
    #import <AudioToolbox/AudioServices.h>

    @implementation TheSound
    @synthesize yayFileID;

    - (void) initSound {
        NSString *yayPath = [[NSBundle mainBundle] pathForResource: @"yay" ofType: @"wav"];
        CFURLRef yayURL = (__bridge CFURLRef) [NSURL fileURLWithPath:yayPath];
        AudioServicesCreateSystemSoundID(yayURL, &yayFileID);
    }

    @end

MainViewController.h:

    #import <UIKit/UIKit.h>
    #import "TheSound.h"

    @interface MainViewController : UIViewController

    - (IBAction) playSound: (id) sender;

    @end

MainViewController.m:

    #import "MainViewController.h"
    #import <AudioToolbox/AudioServices.h>
    #import "TheSound.h"

    @interface MainViewController ()
    @property SystemSoundID yayFileID;
    @property (nonatomic) TheSound *foo;
    @end

    @implementation MainViewController
    @synthesize foo;

    - (void)viewDidLoad {
        [foo initSound];
        [super viewDidLoad];
    }


    - (IBAction)playSound:(id)sender {
        AudioServicesPlaySystemSound(_yayFileID);
    }

    @end

Help as to what I'm doing wrong would be much appreciated! Thanks in advance!

Was it helpful?

Solution

Here

- (IBAction)playSound:(id)sender {
    AudioServicesPlaySystemSound(_yayFileID);
}

the variable _yayFileID refers to a variable in your MainViewController which is completely unrelated to the yayFileID variable in TheSound object.

Maybe if you try

AudioServicesPlaySystemSound(foo.yayFileID);

Even if you do this, I don't think it will work, because additionally, your foo variable is not initialized, so the call initSound is being sent to null. You should do something like this

foo = [[TheSound alloc] init];
[foo initSound];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top