AVPlayer not playing audio - iOS 9, Objective - C

蓝咒 提交于 2019-12-04 11:35:26

问题


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

回答1:


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!




回答2:


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

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

And some documentation



来源:https://stackoverflow.com/questions/33147928/avplayer-not-playing-audio-ios-9-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!