0

I want to play a sound in format wav/mp3. I am using AVAudioPlayer. The issue is its audible in earpiece but when i remove the earpiece no sound comes. I have searched and tried some suggestion given here but the result was same. Please help me with this issue. Thanks

- (void)viewDidLoad
{
    [super viewDidLoad];
       NSString *path = [NSString stringWithFormat:@"%@/Right Side Stress Increasing.mp3", [[NSBundle mainBundle] resourcePath]];
        NSURL *soundUrl = [NSURL fileURLWithPath:path];

        // Create audio player object and initialize with URL to sound
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
}

- (IBAction)playButtonTapped:(id)sender
{
    //play sound
     [_audioPlayer play];
}

2 Answers2

1

AVAudioPlayer don't play sound, if the device is on silent mode.

You can enable using AVAudioSession

OBJECTIVE-C

#import <AVFoundation/AVFoundation.h>

NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];
[[AVAudioSession sharedInstance] setActive:YES error:&error];

SWIFT

import AVFoundation

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    try AVAudioSession.sharedInstance().setActive(true)
}
catch {
    print(error)
}
Harshal Valanda
  • 5,331
  • 26
  • 63
0

Set the volume to max. 1.0 is the maximun volume level 0.0 is minimum volume level

  - (void)viewDidLoad
    {
        [super viewDidLoad];
           NSString *path = [NSString stringWithFormat:@"%@/Right Side Stress Increasing.mp3", [[NSBundle mainBundle] resourcePath]];
            NSURL *soundUrl = [NSURL fileURLWithPath:path];

            // Create audio player object and initialize with URL to sound
            _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
            _audioPlayer.volume = 1.0
    }

    - (IBAction)playButtonTapped:(id)sender
    {
        //play sound
         [_audioPlayer play];
    }
Naresh
  • 869
  • 8
  • 17