AVPlayer不播放音频 - iOS 9,Objective - C

Roh*_*nap 7 objective-c avplayer ios9 xcode7 avplayerviewcontroller

我正在尝试从我的应用程序中的URL播放音频.一切都在iOS 8(模拟器和物理设备)中按预期发生.对于iOS 9,它可以在模拟器中工作,但在设备上,音频根本无法播放.流式传输出现,如果我点击播放,进度条也会显示音频正在加载和播放,但声音没有出现.此问题发生在iOS 9物理设备中.它适用于iOS 8物理设备.

我创建了一个简单的按钮.单击按钮,将加载AVPlayerViewController,并使用给定的URL初始化AVPlayer.代码如下:

#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
Run Code Online (Sandbox Code Playgroud)

Roh*_*nap 29

经过各种试验和错误策略超过5天,我终于发现我的问题是手机的静音开关.当它处于静音状态时,音频不会播放!所以,我添加了以下代码行来指定我的类别作为播放,现在它甚至在我的设备开关处于静音状态时播放

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
Run Code Online (Sandbox Code Playgroud)

谢谢!


Cha*_*ris 5

对于任何有同样问题的人,这里是 Swift 解决方案。

try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
Run Code Online (Sandbox Code Playgroud)

和一些文档