Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVPlayer not playing audio - iOS 9, Objective - C

I am trying to play audio from a URL in my app. Everything happens as expected in iOS 8 (simulator and physical devices). For iOS 9, it works in simulator but on device, the audio simply does not play. The streaming appears, if I click on play, the progress bar also shows that audio is getting loaded and playing but the sound does not come. This issue is happening in iOS 9 physical device. It works totally fine with iOS 8 physical device.

I created a simple button. On clicking on button, the AVPlayerViewController is loaded and AVPlayer is initialized with the given URL. The code is following:

#import "ViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)playAudio:(id)sender {
    NSURL *url = [NSURL URLWithString:@"https://path/to/my.mp3"];
    [self performSegueWithIdentifier:@"playSegue" sender:url];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    AVPlayerViewController *viewController = (AVPlayerViewController *)segue.destinationViewController;
    viewController.player = [AVPlayer playerWithURL:(NSURL *)sender];
}

@end
like image 541
Rohan Sanap Avatar asked Oct 15 '15 11:10

Rohan Sanap


2 Answers

After doing various trial and error tactics for over 5 days, I finally figured out that my problem was with the mute switch of the phone. When it is on mute, the audio does't play! So, I added the following line of code to specify my category as playback and now it plays even when my device switch is on mute

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

Thank you!

like image 62
Rohan Sanap Avatar answered Oct 08 '22 21:10

Rohan Sanap


For anyone with this same issue, here is the Swift solution.

try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])

And some documentation

like image 21
CharlieNorris Avatar answered Oct 08 '22 21:10

CharlieNorris