9

我正在尝试从我的应用程序中的 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
4

2 回答 2

32

经过5天多的反复试验,我终于发现我的问题出在手机的静音开关上。当它静音时,音频不播放!因此,我添加了以下代码行以将我的类别指定为播放,现在即使我的设备开关处于静音状态,它也会播放

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

谢谢!

于 2015-10-29T04:18:38.760 回答
5

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

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

和一些文档

于 2018-02-10T14:39:53.663 回答