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
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!
For anyone with this same issue, here is the Swift solution.
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
And some documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With