2015-10-15 85 views
5

我试图从我的应用程序中的URL播放音频。一切都如预期在iOS 8(模拟器和物理设备)中发生。对于iOS 9,它可以在模拟器中工作,但在设备上,音频根本无法播放。流媒体出现后,如果我点击播放,进度条也显示音频正在加载并播放,但声音不会来。这个问题发生在iOS 9物理设备上。它适用于iOS 8物理设备。AVPlayer不播放音频 - iOS 9,目标 - C

我创建了一个简单的按钮。点击按钮时,AVPlayerViewController被加载,并且AVPlayer使用给定的URL进行初始化。代码如下:

#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 
+0

是url零在你准备SEGUE? –

+0

不,我做了NSLog(“%@”,(NSURL *)sender),它给了我日志中的URL。 –

回答

24

做各种尝试和错误的战术超过5天之后,我终于想通了,我的问题是与手机的静音开关。当它静音时,音频不会播放!所以,我说下面的代码行,指定我为类播放,现在当我的设备开关处于静音状态,

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

谢谢你甚至扮演着!

+1

保存我的屁股。感谢 –

+0

此代码也适用于我,谢谢,但我无法在iPhone中找到您正在谈论的交换机。这是静音? –

+1

@ArpitBParekh我提到的开关位于音量摇杆按钮上方的左侧面板上方。如果代码工作和帮助你,upvote将非常感谢:) –

1

对于有这个问题的人,这里是Swift解决方案。

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

有些documentation