views:

98

answers:

1

Hi all, I have an app that is nearly finished but encountered an annoying problem. In the app, I want to play a sound when I tap on some object, then the object disappears. This is the piece of code I used:

In Object.h

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

@interface Object: UIView {
    UIImageView *image;
    CGPoint location;
    SystemSoundID soundFileID;
}

In Object.m

- (void)initWithSound {
    //a bunch of code to define the image and location
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"caf"];
    CFURLRef soundURL = (CFURLRef)[NSURL fileURLWithPath:soundPath];
    AudioServicesCreateSystemSoundID(soundURL, &soundFileID);
    return self;
}

Then in my mainViewController, several objects will be created upon user's action and added to the screen at different locations with different images. Upon tapping on the object itself, it will create a sound and disappear.

In Object.m

- (void)tapped {
    AudioServicesPlaySystemSound(soundFileID);
    image.image = nil;
    [self removeFromSuperview];
}

Everything works find in the simulator. But when I tried that in iPhone, the object disappears on tapping as expected but the sound just doesn't play. Tried on a 3G and a 3GS, both don't play the sound. I think this should work. Am I making any mistakes? Thanks for any help.

EDIT: Just think of something that I don't know related or not. I'm also using the microphone to detect sound input from the user by AVAudioRecorder. Not sure if this would affect the audio output.

A: 

Finally found where the problem is!!

It turns out that I have to I have to set up an audio session. It's just that! Obviously I need more study on the audio and video things.

Just for someone who may run into the same situation as me, here is the code I added in the viewDidLoad method:

AVAudioSession * audioSession = [AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];

[audioSession setActive:YES error: &error];
Anthony Chan