views:

177

answers:

1

I am writing an iPhone app that when a certain thing occurs, a sound is played. I have trying using different WAV, MP3, M4A files and have intermittent problems. The below code works fine in the simulator but the MP3 does not play on the iPhone. (3GS if it matters). Any ideas? I have changed the mp3 file to a wav and it will work for the one supplied below (knock_knock), but not another. Possibly the way it is encoded?

Any help is appreciated. Thanks

Here is the code:

SystemSoundID soundID;
NSString *soundFile;

if (something == somethingelse) {
    soundFile = [[NSBundle mainBundle] pathForResource:@"knock_knock" ofType:@"wav"];
}
else {
   soundFile = [[NSBundle mainBundle] pathForResource:@"strike" ofType:@"mp3"];
}
   AudioServicesCreateSystemSoundID((CFURLRef)
                                 [NSURL fileURLWithPath:soundFile]
                                 , &soundID);
AudioServicesPlaySystemSound(soundID);
+1  A: 

System sounds have to be uncompressed. I ran into this and changed my code to use AVAudioSession, and AVAudioPlayer. Of the top of my head, something like this (needs better error checking)

    -(void)load {
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: [self path]];
    if (fileURL) {

        AVAudioPlayer *newPlayer =
        [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                               error: nil];
        [fileURL release];
        [self stop];
        self.player = newPlayer;
        [newPlayer release];

        [self.player prepareToPlay];
    }   
}

    -(void)play {

    if (self.player == nil)
        [self load];

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory: AVAudioSessionCategoryAmbient error:&err];
    if(err){
        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }
    [audioSession setActive:YES error:&err];

    self.player.currentTime = 0;
    [self.player play]; 
}
Steve Riggins
This is exactly what I needed...thanks so much!
George