Avaudioplayer lens does not play sound

I use this function to play sound in an application for iPhone. The problem is that the sound does not play. The function works correctly and reads the file path correctly, and I get no errors, but the sound does not play.

-(void) playSound : (NSString *) fName; {
    if ([audioPlayer isPlaying]) {
        [audioPlayer stop];
    }
    audioPlayer.volume = 1.0;
    soundpath = [NSString stringWithFormat:@"sounds/%@", fName];
    soundFilePath = [[NSBundle mainBundle] pathForResource:soundpath  ofType: @"mp3"];
    soundURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
    audioPlayer.numberOfLoops = -1;
    if (audioPlayer == nil){

    }
else {
    [audioPlayer play];
        if ([audioPlayer isPlaying]) {
            NSLog(@"%@", @"run");
     }
}
}
+3
source share
1 answer

Try adding this:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error: nil];
UInt32 route = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof(route), &route);

I had a similar problem and adding this before calling the game, it solved the problem for me.

+5
source

All Articles