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

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.

Related

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);
}

iOS: Playing audio in silent mode [duplicate]

This question already has answers here:
Play sound on iPhone even in silent mode [duplicate]
(8 answers)
Closed 9 years ago.
What is the "correct" way to get my app to play audio even if the user's silent/mute switch is set to silent/vibrate?
Some background:
I actually got it working in debug stage, but when I submitted my app to Apple and then later downloaded it from the app store, the audio was disabled in silent mode! Here is how I got it working in debug stage:
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
sizeof(sessionCategory), &sessionCategory);
Audio was played using:
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"];
AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
I think it does the same thing, but have you tried, setting the setting throught AVFoundation like so?
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];

how to play music using AVAudioPlayer when screen os locked

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**];

How to record and play sound in iPhone app?

I tried using AVAudioSession and AVAudioPlayer to record and play sounds respectively but the sound volume is very low.
I tried putting volume value of AVAudioPlayer to 1.0 and more but didn't help much.
What could be my other options to record sound which can be loud enough to play back?
This code should be useful for you:
#import <AudioToolbox/AudioServices.h>
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
sizeof (audioRouteOverride),&audioRouteOverride);
It will increase volume. The functionality of the code is to convert the ordinary sound to speaker sound on ur iPhone. That's why kAudioSessionOverrideAudioRoute_Speaker is used.
Since iOS7 you can fix this issue directly with AVAudioSession
The overrideOutputAudioPort method does the same than AudioSessionSetProperty
NSError *setOverrideError;
NSError *setCategoryError;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];
if(setCategoryError){
NSLog(#"%#", [setCategoryError description]);
}
[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&setOverrideError];
if(setOverrideError){
NSLog(#"%#", [setOverrideError description]);
}
Swift version :
import AVFoundation
var overrideError : NSError?
if AVAudioSession.sharedInstance().overrideOutputAudioPort(.Speaker, error: &error){
}else{
print("error in overrideOutputAudioPort " + overrideError!.localizedDescription)
}
Swift 2:
do {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker)
} catch {
}
The following code fixed this issue for me:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error: nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
UInt32 doChangeDefault = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefault), &doChangeDefault);
MAN, try this.
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
if (![session setCategory:AVAudioSessionCategoryPlayback
withOptions:kAudioSessionOverrideAudioRoute_Speaker
error:&setCategoryError]) {
// handle error
}
NSError *error;
NSData * data = [NSData dataWithContentsOfURL:self.playlet.urlSound];
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:data fileTypeHint:#"aac" error:&error];
self.audioPlayer.delegate = self;
if (error)
NSLog(#"Error: %#",
[error localizedDescription]);
else
[_audioPlayer play];
just set this
[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&setOverrideError];
It works for me.

playing audio files from table, iphone

I've created a list of music file names in an array which is used to populate an uitableview. I want to make the audio player take this array or table as the playlist and play them continuously one by one, with all the features like play, pause, next, previous, forward, backward and stop. What is the best way to implement this. All the music files in the resource folder itself so that i can initiate each one as
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"mp3"];
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = newURL;
[newURL release];
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
self.appSoundPlayer = newPlayer;
[newPlayer release];
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 1.0];
[appSoundPlayer setDelegate: self];
Could this be as simple as implementing the AVAudioPlayerDelegate?
appSoundPlayer.delegate=self;
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (successfully)
{
// play next track
}
}
Obviously you'd need to keep track of which track is currently playing in order to work out the next track to play, but that shouldn't be a problem. You'd also have to implement your own controls and logic for track skip etc, but again this is easily done.