AVPlayer does not play audio - iOS 9, Objective - C

I am trying to play audio from a url in my application. Everything happens as expected in iOS 8 (simulator and physical devices). For iOS 9, it works in the simulator, but the sound simply does not play on the device. The stream appears if I click on the game, the progress bar also shows that the sound is loading and playing, but the sound does not appear. This issue occurs on the iOS 9 physical device. It works fine with the iOS 8 physical device.

I created a simple button. When you click on the button, the AVPlayerViewController is loaded and the AVPlayer is initialized with the given URL. The code is as follows:

#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 
+5
source share
2 answers

After doing various trial and error for more than 5 days, I finally realized that my problem was with the phone turned off. When it is muted, sound is not played! So, I added the following line of code to indicate my category as playback, and now it plays even when my device switch is off

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

Thanks!

+24
source

For those who have the same problem, here is the Swift solution.

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

And some documentation

+1
source

Source: https://habr.com/ru/post/1233777/


All Articles