How to play multiple audio files in the background in iOS 4? - iphone

I ran audio in the background in my iPhone app using AVAudioPlayer and AVAudioSession...
Now my problem is that I already have a written code that takes a number of songs as input from the user and plays them one after the other using AVAudioPlayer...
The problem is that when the app goes to the background while one of the files is being played, the audio continues but when it's done, the sound disappears... In foreground when a file is done, I just do some code to play the next one but in the background this is not possible...
I thought about requesting some time to get this done and run my code but I can't do this as the audio files always change and they might be long... So please tell me what should I do? Is there any built-in playlist player that run as a background audio? or is there any other solution? I really need to get this into work...
thanks a lot

I ran into the same issue and haven't completely resolved it yet. The audioDidFinishPlaying delegate method still fires, and you can use UIAplication's beginBackgroundTask to create a new instance of AVaudioPlayer, make sure AVAudioSession is still active, etc. But when I try to play the new AVAudioPlayer instance, it pauses immediately. My suspicion/fear is that there is no way to start the audio FROM the background, only keep it playing when the application state transition happens. I'd love to be wrong, though.

this is easy ..just change the cateogry if your using an audio session that is ...
http://developer.apple.com/library/ios/#documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionCategories/AudioSessionCategories.html
the link has the categories ...so use one of these and you be able to start the sound in the background:
AVAudioSessionCategoryPlayback
kAudioSessionCategory_MediaPlayback
the ambient one might not work.

//ViewController.h ,write below code
#interface ViewController : UIViewController<AVAudioRecorderDelegate,AVAudioPlayerDelegate>
//assign property to player
#property(nonatomic,retain) AVAudioPlayer *player;
//then write in ViewController.m file in ViewDidLoad Method below code
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
NSError *soundError;
NSString *path=[[NSBundle mainBundle]pathForResource:#"soundFileName" ofType:#"mp3"]; //.mp3 file for player
NSURL *file=[[NSURL alloc]initFileURLWithPath:path]; //path
_player=[[AVAudioPlayer alloc]initWithContentsOfURL:file error:&soundError]; //player Object
if(_player == nil)
{
NSLog(#"player is empty because of %#",soundError);
}
else
{
[_player play];
_player.volume=1.0;
[_player setDelegate:self];
}
// for stop player you can use
// [_player stop]; //uncomment this line when you wants to stop it.

Related

Play sound in background using AVAudioPlayer without stopping ipod music

In my app at particular time i am alerting user with beep sound which i am playing using AVAudioPlayer.
Now i want this sound to be played even when app is in background. So i can achieve this by setting AVAudioSession category as AVAudioSessionCategoryPlayback and i also want that this sound should not stop the ipod music and i can do it with it setting AVAudioPlayer category AVAudioSessionCategoryAmbient.
But i want them together means sound should also play in background and it should also not stop the ipod music.
So how can i achieve this?
If it is not possible to play sound with AVAudioSessionCategoryAmbient category in background then any other workaround this?
Apologies if i am doing any mistake.
Thanks.
you need to add one row in your project.plist file Required background modes like bellow image and set it.
and put bellow code in to your project appdelegate didFinishLaunchingWithOptions
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
NSError *error;
BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
if (!success) {
//Handle error
NSLog(#"%#", [error localizedDescription]);
} else {
// Yay! It worked!
}
its working for me hope its useful for you my frnd al the best.
UPDATE
You can't run AVAudioPlayer and the iPod player or MPMusicPlayer or MPMoviePlayer at the same time, without doing a bit more work. If you want easy, then use Audio Toolbox's System Sounds.
please refer this bellow link:-
iPhone AVAudioPlayer stopping background music
Please check bellow Link there are demo of Playing audio file in background. please check it
http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_background-audio/

iphone app allow background music to continue to play

When I launch my iPhone game as soon as a sound plays the background music or podcast that is playing stops. I noticed other games allow background audio to continue to play.
How is this possible? Do I need to override a method in my App Delegate?
Place this line in your application:didFinishLaunchingWithOptions: method of your AppDelegate or in general before using the audio player.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
According to the documentation, the AVAudioSessionCategoryAmbient category is
for an app in which sound playback is nonprimary—that is, your app can be used successfully with the sound turned off.
This category is also appropriate for “play along” style apps, such as a virtual piano that a user plays over iPod audio. When you use this category, audio from other apps mixes with your audio. Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone).
If you want also to ensure that no error occurred you have to check the return value
NSError *error;
BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
if (!success) {
//Handle error
NSLog(#"%#", [error localizedDescription]);
} else {
// Yay! It worked!
}
As a final remark, don't forget to link the AVFoundation framework to your project and import it.
#import <AVFoundation/AVFoundation.h>

How to resume background music after out-going phone call (iOS)?

I'm using AVAudioPlayer to play music (background supported). My question is if I want to call somebody while I'm listening to the music, how to resume it after the call? I've implement the AVAudioPlayer's delegate method:
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)thePlayer {
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[self.player play];
}
but this will not allow the music to continue.
I've also tried to use the AVAudioSessionDelegate method (just a try):
- (void)viewDidLoad {
[[AVAudioSession sharedInstance] setDelegate:self];
}
- (void)endInterruption
{
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[self.player play];
}
but again this won't cause the music to resume. Any ideas about how to solve this problem?
strange from your code is, you're telling that you do use AVAudioPlayer, why do you then implement AVAudioSessionDelegate?
And you have bad implementation of delegate methods. See docs
from AVAudioPlayerDelegate:
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withFlags:(NSUInteger)flags
So try to implement them like this, and it should be working properly
On iOS, an app can not start playing audio when already in the background. If your app's audio is stopped because a foreground app has taken control of the audio session, there is (currently) no way to take it back.
You can resume it. After finishing your audio session you have to notify other app that my app deactivate the audio session and you can make use of it. Use the following code.
[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];

MPMoviePlayerController multitasking problem

I develop an application on iphone that uses MPMoviePlayerController to play audio file.
When Application goes to background, if mpmovieplayer is playing, iphone continues to play the current music, but when it ends, the next track doesn't start.
I try to start the next audio file in the MPMoviePlayerPlaybackDidFinishNotification and when I follow the code using the debugger I can see that the method is invoked and the code executed, bat the next audio file still doesn't start.
Is this possible on iOS 4.1 or this is a limitation?
Best regards
Samantha
You should read the Technical Q&A QA1668:
How to play audio in the background with MPMoviePlayerController.
Summary of the steps needed:
declare that your application supports background execution for audio
assign an appropriate category to your audio session (default category is not ok)
I got it working by putting following two lines in Delegate file:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
may be you forget to add this in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

Using Finch to play sounds on iphone

I have an application which has two kinds of sounds:
1. Background sounds, looping forever till next view.
2. Sounds clips that could be played separately or all in one go.
Previously i tried using AVAudioPlayer but there was always a very little silence interval between two clips (to which i didn't find any solution, if you have one, please post in reply), so shifted to Finch e.g. http://github.com/zoul/Finch/tree/master
Now here is the deal:
I am using AVAudioPlayer to play looping forever sounds while Finch to play those back-to-back clips. I am doing this:
- (void)viewDidLoad {
[super viewDidLoad];
soundEngine = [[Finch alloc] init];
/***
CLIPPED
***/
}
-(void) playclip:(id) sender {
NSString *fullPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"sitar.wav"];
NSLog(#"Song is %#", fullPath);
clip = [[Sound alloc] initWithFile:fullPath];
NSLog(#"Clip Length: %#", clip.length);
NSLog(#"Clip Playing ? : %d", clip.playing);
[clip play];
NSLog(#"Played Clip");
}
This is almost same code as the demo project provided as in the git repository. But for some reason i get this on console:
Song is /Users/shoaibi/Library/Application Support/iPhone Simulator/User/Applications/17FBA26F-6047-4D56-9E45-ADAFE07B7234/Test.app/sitar.wav
Failed to create OpenAL source, error code a004.
Clip Length: (null)
Clip Playing ? : 0
Played Clip
An ls on the directory printed on console reveals that there is sitar.wav there with the correct permissions. What could be the issue? may be the background sound AVAudioPlayer which i stop using:
- (void)viewWillAppear:(BOOL)animated {
//Stop the background music before my ears bleed :P
d = [[UIApplication sharedApplication] delegate];
if (d.bg.playing)
{
[d.bg stop];
NSLog(#"Background music stoped");
}
}
is not freeing up sound resource?
Latest Finch now checks whether OpenAL is initialized when you initialize a new Sound. If current OpenAL context is not set because you forgot or failed to initialize Finch, you get a better error message. Give it a try, it might be the case that your initialization code is buggy.
I got the same error when I called the sound clip allocs in my viewWillAppear - seems it was called before the awakeFromNib finished doing its stuff. Anyway, shifting the allocs so they happened later fixed it.