开发者

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

开发者 https://www.devze.com 2022-12-17 21:55 出处:网络
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

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

精彩评论

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

关注公众号