user3218241 user3218241 - 4 months ago 23
Objective-C Question

AVAudioPlayer does not give error but not playing sound

Hello I am completely new to apple development

i run the code on my iPhone there is no error but i can not hear the sound
here is the code

-(void) buttonPressed1:(UIButton *)sender{
NSString *fileName = @"Record_000";
NSLog(@"%@", fileName);
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];
self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
self.theAudio.volume = 1.0;
[self.theAudio prepareToPlay];
[self.theAudio play];
}


this is my h file

#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
@interface StartPage : UIViewController
@property (nonatomic, strong) AVAudioPlayer *theAudio;
@end

Answer

Try to set the audio session:

#import <AVFoundation/AVAudioSession.h>

    -(void) viewDidLoad
    {
        [super viewDidLoad];
        [self setAudioSession];
    }

    -(void) setAudioSession
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        NSError *sessionError = nil;
        BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
        if (!success)
        {
            NSLog(@"Setting Audio Session Category Error: %@", sessionError);
        }
        success = [audioSession setActive:YES error:&sessionError];
        if (!success)
        {
            NSLog(@"Setting Audio Session Active Error: %@", sessionError);
        }
    }
Comments