Search code examples
iosobjective-cxcode8avaudioplayervolume

ObjectiveC AVAudioPlayer volume is 0


I've seen quite many posts about AVAudioPlayer but nones helps: I cannot get sound anymore (even though it used to work with Xcode before upgrade to 8.3.2)

Here is my code:

AVAudioPlayer *audioPlayerObj;
AVAudioSession *session;
[...]
- (IBAction)playSound:(id)sender {
audioPlayerObj.delegate = self;

if(playButton.isSelected){        
    playButton.selected=NO;
    (void) [audioPlayerObj stop];
}
else{
    session = nil;
    {NSError * _error;

        session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayback
                       error:&_error];
        [session setActive:YES error:&_error];
        if(_error !=nil)
        {   NSLog(@"could not init the audio player session %@ ", _error);
        }

    }

    NSString * tune =[NSString stringWithFormat:@"%@.wav",[pickerViewArray objectAtIndex:[pickerView selectedRowInComponent:0]]];
    NSString *path =[[NSBundle mainBundle] pathForResource:tune ofType:@""];

    NSURL * actualFilePath= [NSURL fileURLWithPath:path];
NSError *error;

(void)[audioPlayerObj initWithContentsOfURL:actualFilePath error:&error];

    [audioPlayerObj prepareToPlay];


    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
    [audioPlayerObj setVolume:0.99 fadeDuration: 1];

    }
    NSLog(@"syst volume : %f", [session outputVolume]);
    NSLog(@"vol : %f\n",[audioPlayerObj volume] );

if(error !=nil)
{   NSLog(@"could not init the audio player %@ ", error);
    audioPlayerObj=nil;

}
else
{
    (void) [audioPlayerObj setNumberOfLoops:-1  ];
    (void) [audioPlayerObj play];
    NSLog(@"playing with vol : %f\n",[audioPlayerObj volume] );
    [audioPlayerObj setVolume:0.99 fadeDuration: 1];
    playButton.selected=YES;
}
}

`

The output is syst volume : 0.476119 vol : 0.000000 playing with vol : 0.000000 Any hint on how to raise that volume would be appreciated. The view also has a MPVolumeView, but any action on it would only change the system volume.


Solution

  • the mistake was here:

    (void)[audioPlayerObj initWithContentsOfURL:actualFilePath error:&error];
    

    should have been:

     audioPlayerObj = [[AVAudioPlayer alloc] initWithContentsOfURL:actualFilePath error:&error];