how to play music using AVAudioPlayer when screen os locked - iphone

i need to play a simple sound using AVAudioPlayer when screen is locked .How can I do that please help

This was answered here before. As the thing suggests you need to set your audio session as in this example
UInt32 category = kAudioSessionCategory_MediaPlayback;
OSStatus result = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
sizeof(category), &category);
if (result){
DebugLog(#"ERROR SETTING AUDIO CATEGORY!\n");
}
result = AudioSessionSetActive(true);
if (result) {
DebugLog(#"ERROR SETTING AUDIO SESSION ACTIVE!\n");
}

First: Add following frameworks into your project
AudioToolbox,
CoreAudio,
MediaPlayer
AVFoundation.
Second: Add your info.plist file a new key
Required background modes = App plays audio
Third: Create a method called keepAwakeForAudio and call it just after playing your audio
-(void)keepAwakeForAudio
{
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (sessionCategory), &sessionCategory);
AudioSessionSetActive(true);
}
//////
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/rain1_Rain_on_Street.m4a", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
[self **keepAwakeForAudio**];

Related

iOS sound playback volume not respecting volume change or mute

This is my current code
void playSound(NSString* myString) {
CFBundleRef mainBundle = CFBundleGetMainBundle();
NSString *string = myString;
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle,
(__bridge CFStringRef) string, CFSTR ("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
}
It works, but it doesn't let you change the volume on the device or mute it with the mute switch. What is the simplest way to enable these features? Thanks.
Why don't you use AVFoundation? If all you want is to play simple sound effects, it would be a much better choice as it is a higher level API.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"mp3"];
NSURL *url = [NSURL fileURLWithPath:filePath];
// Assuming audioPlayer is an ivar.
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
AVAudioPlayer should respect the volume settings of the user.

Using AVCaptureSession and AVAudioPlayer together

I am able to record video and output the movie to a file correctly. However, I have a problem with video recording (no video ouput) when trying to use AVAudioPlayer to play some audio. Does it mean that I cannot use AVCaptureSession and AVAudioPlayer at the same time? Here is my code to create the capture session and to play the audio. The video capture is started first, then during the capturing, I want to play some audio. Thanks so much for any help.
Code to create the capture session to record video (with audio) - output to a .mov file:
- (void)addVideoInput
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
//... also some code for setting up videoDevice/frontCamera
NSError *error;
AVCaptureDeviceInput *videoIn = [AVCaptureDeviceInput
deviceInputWithDevice:frontCamera error:&error];
AVCaptureDeviceInput *audioIn = [AVCaptureDeviceInput
deviceInputWithDevice:audioDevice error:&error];
if (!error) {
if ([captureSession canAddInput:audioIn])
[captureSession addInput:audioIn];
else
NSLog(#"Couldn't add audio input.");
if ([captureSession canAddInput:videoIn])
[captureSession addInput:videoIn];
else
NSLog(#"Couldn't add video input.");
}
- (void)addVideoOutput
{
AVCaptureMovieFileOutput *m_captureFileOutput = [[AVCaptureMovieFileOutput alloc] init];
[captureSession addOutput:m_captureFileOutput];
[captureSession startRunning];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSMutableString *filePath = [NSMutableString stringWithString:#"Movie.mov"];
NSString* fileRoot = [docDir stringByAppendingPathComponent:filePath];
NSURL *fileURL = [NSURL fileURLWithPath:fileRoot];
AVCaptureConnection *videoConnection = NULL;
for ( AVCaptureConnection *connection in [m_captureFileOutput connections] )
{
for ( AVCaptureInputPort *port in [connection inputPorts] )
{
if ( [[port mediaType] isEqual:AVMediaTypeVideo] )
{
videoConnection = connection;
}
}
}
[videoConnection setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];
[m_captureFileOutput startRecordingToOutputFileURL:fileURL recordingDelegate:self];
[m_captureFileOutput release];
}
Code to play the audio, this function is call during the video capture session. If I don't call this function, the video is recorded and I am able to save to the .mov file. However, if I call this function, there's no output .mov file.
- (void)playAudio
{
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"AudioFile" ofType:#"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[fileURL release];
self.audioPlayer = newPlayer;
[newPlayer release];
[audioPlayer setDelegate:self];
[audioPlayer prepareToPlay];
[audioPlayer play];
}
I fixed the problem by setting up the audio session. I called the following function before creating the audio player object to play the audio. That way, I was able to record video (with audio) and play audio at the same time.
- (void)setupAudioSession {
static BOOL audioSessionSetup = NO;
if (audioSessionSetup) {
return;
}
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doSetProperty), &doSetProperty);
[[AVAudioSession sharedInstance] setActive: YES error: nil];
audioSessionSetup = YES;
}
- (void)playAudio
{
[self setupAudioSession];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"AudioFile" ofType:#"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[fileURL release];
self.audioPlayer = newPlayer;
[newPlayer release];
[audioPlayer setDelegate:self];
[audioPlayer prepareToPlay];
[audioPlayer play];
}

App sounds cause iPod music, Pandora or Pod cast sound to stop

we have different sounds for actions and buttons within our app. We've heard a number of complaints where users background music stops as soon as one of our sounds is played. We're not quite sure why this is happening. Here is the code we're using to toggle our sounds.
- (void)playSound:(NSString *)sound {
if ( playSoundPath == nil ) {
playSoundPath = [[NSBundle mainBundle] pathForResource:sound ofType:#"wav"];
playSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:playSoundPath] error:NULL];
playSound.delegate = self;
}else{
playSoundPath = nil;
[playSound release];
playSoundPath = [[NSBundle mainBundle] pathForResource:sound ofType:#"wav"];
playSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:playSoundPath] error:NULL];
playSound.delegate = self;
}
BOOL enabled = [[NSUserDefaults standardUserDefaults] boolForKey:#"sounds_key"];
if ( enabled ){
[playSound stop];
[playSound play];
}
}
Update: We've actually ended up changing the above to the following per a few users suggestions. This allows iPod music or pod casts to continue and our sounds to play without stopping this background sound. This is possible by setting our sounds as "ambient" sound. This requires that you add the "AudioToolBox" framework and import this framework into your class using the following,
#import <AudioToolbox/AudioToolbox.h>
Here is the code we're using now,
BOOL enabled = [[NSUserDefaults standardUserDefaults] boolForKey:#"sounds_key"];
if ( enabled ){
AudioSessionInitialize(NULL, NULL, NULL, self);
UInt32 category = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
AudioSessionSetActive(YES);
NSString *path = [NSString stringWithFormat:#"%#/%#.wav",[[NSBundle mainBundle] resourcePath], sound];
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
}

Sound does not play while using AVAudioPlayer

Here is my code on button click
- (void)playButton:(id)sender
{
NSLog(#"Play Button Clicked!!!...");
audioPlayer = [self setUpAudioPlayer:[songs objectAtIndex:i]];
}
-(AVAudioPlayer *)setUpAudioPlayer:(NSString *)filename
{
NSLog(#"File name : %#",filename);
NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:#"caf"];
NSLog(#"File path = %#",path);
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
//audioPlayer.volume = 0.5;
[audioPlayer prepareToPlay];
[audioPlayer play];
NSLog(#"Song is playing....");
return [audioPlayer autorelease];
}
here songs is NSMutableArray which contains file name... All things go correct with NSLog... But no sound is coming and no error comes.. What is wrong with the code..???
Your audio player is probably getting released as soon as it starts playing. Try to retain it after setUpAudioPlayer is called.
Most probably you need to initialize an audio session, some like this
- (void)setupAudioSession
{
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error = nil;
[session setCategory: AVAudioSessionCategoryPlayback error: &error];
if (error != nil)
NSLog(#"Failed to set category on AVAudioSession");
// AudioSession and AVAudioSession calls can be used interchangeably
OSStatus result = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, RouteChangeListener, self);
if (result) NSLog(#"Could not add property listener! %d\n", result);
BOOL active = [session setActive: YES error: nil];
if (!active)
NSLog(#"Failed to set category on AVAudioSession");
}

iPhone: How to play a sound on top of the iPod sound?

I'm trying to play a sound on top of the iPod music but when I enter my app the iPod sound is silenced automatically. I tried:
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
sizeof (sessionCategory),
&sessionCategory
);
But probably because I use RemoteIO/Audio Units to play my sound this has no effect (not sure if that's the cause, but it sure thing does nothing ... the sound still stops)
I am missing something?
For some reason, the code in the question doesn't work, however this works:
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
AudioSessionSetProperty returns an error, are you checking it?
You may have forgotten to call AudioSessionInitialize, something you don't need to do with the AVFoundation wrapper.
#property (nonatomic, strong) AVAudioPlayer * avAudioPlayer;
NSString *zeroAudioPath = [[NSBundle mainBundle] pathForResource:#"customSound" ofType:#"wav"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:zeroAudioPath];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file
error:nil];
self.avAudioPlayer = audioPlayer;
self.avAudioPlayer.delegate = self;
[_zeroAudioPlayer prepareToPlay];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
[_zeroAudioPlayer play];
Hope it will help you.