1
#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.

Newbie
  • 2,775
  • 6
  • 33
  • 40
  • Are you sure http://localhost is reachable? Are you running a http server? Did you configured and started it correctly? – Samet DEDE Feb 26 '14 at 14:39

3 Answers3

3
[[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

0

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

Duncan C
  • 128,072
  • 22
  • 173
  • 272
-1
#define STREAM @"http://"

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

#define STREAM (@"file://")
Hamid Nazari
  • 3,905
  • 2
  • 28
  • 31