Playing music in background ios app - ios

In my code:
- (void) viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"www/media/BlueZedEx" ofType:#"mp3"]];
AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
NSLog(#"goldenace launchOptions = %#", musicFile);
click.delegate = self;
click.numberOfLoops = -1;
[click play];
}
But nothing music play when I run my app in simulator.
Please help!

use this for Playing Background Audio:
[[AVAudioSession sharedInstance] setDelegate: self];
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
refer this link

This
www/media/BlueZedEx
is not a filename.
It needs to be a filename of a audio file inside your project (drag and drop)

Related

Sounds not playing on iPhone 7 iOS 10

I have apps that play sounds. They play fine on an iPad Air 10.3.1, but not on my iPhone 7 10.3.1. I've tried different audio formats and nothing plays on the iPhone 7. Is there some entry in the plist or some other setting I need to get sounds to play on iPhone 7?
ViewController.h
#property (strong,nonatomic) AVAudioPlayer *player;
ViewController.m
- (void)viewDidAppear:(BOOL)animated {
NSError *err;
NSURL *url = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:#"sound" ofType:#"wav"]];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];
if (err) NSLog(#"error");
player.volume = 1.0;
player.delegate = self;
[player prepareToPlay];
[player play];
NSLog(#"sound should have played");
}
I added this and now it works. Not sure why it worked before on other devices.
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];

AVAudio layer is not playing the sound in ios

Hi in my application I am using UILocalNotifications and AVAudiopPlayer to play a song. When a notification comes I am trying to play a song when I select notification alert. Here is the code, I am getting the sound but isplaying property is setting as YES.
In AppDelegate:
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
MainViewController *main=[[MainViewController alloc]init];
[main playSong:notification.soundName];
}
-(void)playSong:(NSString *)songName
{
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:songName ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
[_audioPlayer setDelegate:self];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
_audioPlayer.numberOfLoops = -1; //Infinite
[_audioPlayer prepareToPlay];
[_audioPlayer play];
}
Replace your code with following code and then try it may be help you.
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
MainViewController *main=[[MainViewController alloc]init];
[main playSong:notification.soundName];
}
-(void)playSong:(NSString *)songName
{
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:songName ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
[_audioPlayer setDelegate:self];
_audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL: soundFileURL fileTypeHint:AVFileTypeMPEGLayer3 error:&errorAudio];
_audioPlayer.numberOfLoops = -1; //Infinite
[_audioPlayer prepareToPlay];
[_audioPlayer play];
}

background audio working on iOS simulator but not device

I'm writing an alarm clock application that works by playing looped silence in the background until it's time for the alarm to fire, at which point it plays the alarm sound on loop until the user opens the app. Here's my code from applicationWillResignActive:
UIApplication *app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier bgTask = 0;
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
NSString *soundPath = [[NSBundle mainBundle] pathForResource:#"silence" ofType:#".wav"];
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[player setNumberOfLoops:-1];
alarmTimer = [NSTimer scheduledTimerWithTimeInterval:timerInterval target:self selector:#selector(playAlarm) userInfo:nil repeats:NO];
[player prepareToPlay];
[player play];
here's the method triggered by the timer:
[player stop];
NSString *soundPath = [[NSBundle mainBundle] pathForResource:#"Alarm" ofType:#".m4r"];
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[player setNumberOfLoops:-1];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[player prepareToPlay];
[player play];
This works as intended when I test it on the simulator. On my iPhone, the timer's method does get called but audio doesn't play. I did add background audio to my plist file. The iPhone's case-sensitivity to the name of the audio file is not the problem and the iPhone's mute switch is off. Thanks for reading!
solved: apparently you can't initiate audio from the background. workaround is to call the method that plays audio from the main thread using performSelectorOnMainThread:withObject:waitUntilDone:.

AVAudioPlayer not playing sounds simultaneously

I am trying to play a couple of sounds files at the same time for the AVAudioPlayer. I read a thread explaining how to do it # AVAudioPlayer Help: Playing multiple sounds simultaneously, stopping them all at once, and working around Automatic Reference Counting . It seems to be a weird issue as I when i try to only play one file at a time (when self.options.on is ON), it works, but when I try creating multiple instances (the else statements) and play them nothing plays. I checked to see if the outputfile URL is correct and it is, so what is the reason that it isn't working?
Thanks!
- (void)playTapped:(id)sender
{
if (!recorder.recording)
{
if(self.options.on)
{
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
[NSString stringWithFormat:#"sound%i.m4a",last],
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:nil];
NSLog(#"%#",player.url);
[player setDelegate:self];
[player play];
}
else
{
// trying to play all sounds at once
for (NSString *str in self.soundsCreated){
NSLog(#"%#",str);
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
[NSString stringWithFormat:#"sound%#.m4a",str],
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:nil];
NSLog(#"%#",audioPlayer.url);
[audioPlayer prepareToPlay];
[audioPlayer setDelegate:self];
[audioPlayer play];
}
}
}
}
NOTE
I tried initializing with NSError check but i'm not getting any errors:
NSError *sessionError = nil;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:&sessionError];
if (sessionError)
{
NSLog(#"Error in audioPlayer: %#",[sessionError localizedDescription]);
}
SOLUTION
It seemed to be an issue with the initialization of my NSMutableArrays.
I changed them from:
self.soundsCreated = [[NSMutableArray alloc]init];
self.playerArray = [[NSMutableArray alloc]init];
to
self.soundsCreated = [NSMutableArray new];
self.playerArray = [NSMutableArray new];
and that fixed it
I have faced the same while played a small file:
Here is my solution (example)
- (void)dropSoundWhileRefresh
{
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
[[AVAudioSession sharedInstance] setDelegate:self];
NSURL *musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"waterDrops" ofType:#"mp3"]];
dropSound = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
[dropSound setDelegate:self];
[dropSound setVolume:0.10];
[dropSound setNumberOfLoops:0];
[dropSound play];
}
Instead of passing error as nil try this and check if initialization is working correct.
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (error)
{
DebugLog(#"Error in audioPlayer: %#",[error localizedDescription]);
}

Output sound to receiver and not to speaker

My audio plays from the speaker and I want it play from the receiver (with a button).
At first I am trying to force the sound to output from the receiver. (I want to be compatible with iOS 3.2)
Here is what i have just after the [super viewDidLoad];
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];
// UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
[[AVAudioSession sharedInstance] setActive:YES error:nil];
and later when I call the play :
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:lblText.text
ofType:#"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
}
[self playAudio];
MPVolumeView *volumeView = [[[MPVolumeView alloc] initWithFrame:[volumeSlider frame]] autorelease];
[volumeSlider removeFromSuperview];
[self.view addSubview:volumeView];
What am I doing wrong ?
Here is the answer :
The override is only applicable to the kAudioSessionCategory_PlayAndRecord category and not to AVAudioSessionCategoryPlayback.
https://developer.apple.com/library/ios/#qa/qa1754/_index.html

Resources