AvAudioSession won't work in iOS7?

匆匆过客 提交于 2019-12-08 06:26:04

问题


#import "SctreamAudioViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SecondViewController.h"

@interface SctreamAudioViewController ()
@property (nonatomic, strong) AVPlayer *player;
@end

@implementation SctreamAudioViewController

#define STREAM @"http://localhost/audio.mp3"

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
[audioSession setActive:YES error:nil];
NSURL *url = [[NSURL alloc] initWithString:STREAM];
self.player = [[AVPlayer alloc] initWithURL:url];
}

- (IBAction)play:(id)sender {

[self.player play];
}

I do quite a lot of researches on the net and I think this should be the right way to play audio in background. However, it just doesn't work out. I have no idea where it goes wrong. Please help. Thanks.


回答1:


[[AVAudioSession sharedInstance] setActive:NO error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];

if you want to play audio when app is in the background, you should use category Playback instead of playAndRecord. Also, you need to check Audio and airPlay in project-> target-> Capabilities-> backgroundMode




回答2:


Look up UIBackgroundModes. You need to tell the system that your app is going to play sound in the background.




回答3:


#define STREAM @"http://"

I believe http is not right in your #define. Try giving it as

#define STREAM (@"file://")


来源:https://stackoverflow.com/questions/20366392/avaudiosession-wont-work-in-ios7

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