I have a tvOS app which attempts to play an audio file like this:
#import "NameViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface NameViewController ()
@end
@implementation NameViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"intro" ofType:@"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL fileTypeHint:AVFileTypeMPEGLayer3 error:nil];
player.numberOfLoops = -1; //infinite
[player play];
}
If I put a breakpoint after [player play]; it starts playing for a few seconds. If I don't have the breakpoint, no audio ever plays.
What am I doing wrong?
This worked by calling play in viewWillAppear:
#import "NameViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface NameViewController ()
@property (strong, nonatomic) AVAudioPlayer *player;
@end
@implementation NameViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createAndStartAudioPlayer];
}
- (void) viewWillAppear:(BOOL)animated{
[self.player play];
}
- (void) createAndStartAudioPlayer {
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"intro" ofType:@"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL fileTypeHint:AVFileTypeMPEGLayer3 error:nil];
self.player.numberOfLoops = -1; //infinite
}