问题
#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