开发者

iPhone not playing mp3 sound using type=@"mp3"

I am writing an iPhone a开发者_开发技巧pp 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);


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]; 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜