How to programmatically mute video - ios

How to play a video without sound?
I have tried these options but neither of them worked:
1) Setting the MPMusicPlayerController player to ipodMusicPlayer and disabling the application audio.
musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
[[MPMusicPlayerController applicationMusicPlayer] setVolume:0];
2) Forcing the app to run the audio
NSError *error = nil;
if ([[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&error]) {
NSLog(#"Error setting audio session: %#", error);
}

Use this codebase to mute.
NSError *errorFeedBack = nil;
if (![[AVAudioSession sharedInstance] setActive:NO error:&errorFeedBack] )
{
NSLog(#"Error encountered: %#", [errorFeedBack localizedDescription]);
}

Related

iOS: AVAudioSession sample rate is not changing when playing a sound from speaker

When setting the preferred sample rate to 16000 it is working fine. However, when I want to play the sound from the speaker and print the sample rate I find it 48000.
I tried to set the sample rate again after playing from the speaker, but it is not working.
NSError *err = nil;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:NO error:&err];
BOOL successfullySatSampleRate = [session setPreferredSampleRate:SAMPLING_FREQUENCY error:&err];
if(err != nil)
{
NSLog(#"Error in setting up audio: %#", err);
}
if(!successfullySatSampleRate)
{
NSLog(#"Error in setting up sample rate");
}
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error: nil];
[session setActive:YES error:&err];
NSLog(#"initialize Session preferredSampleRate = %f, hardware sampleRate = %f",[session preferredSampleRate],[session sampleRate]);
What should I do to keep the sample rate 16000?

Play music in background when home button is press

I want to play music background and for this i made changes in info.plist . I set Applications does not run in background to NO, required background modes to App plays audio.
I added this in AppDelegate :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *error = nil;
NSLog(#"Activating audio session");
if (![audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:&error]) {
NSLog(#"Unable to set audio session category: %#", error);
}
BOOL result = [audioSession setActive:YES error:&error];
if (!result) {
NSLog(#"Error activating audio session: %#", error);
}
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
but music doesn't play anymore when i press home button. Any ideea please where i'am wrong ?
and play audio on homeBtn screen on homeBtnEventMethod
1.) in viewController.h #import <AVFoundation/AVAudioPlayer.h>
2.) #property (nonatomic, strong) AVAudioPlayer *theAudio;
3.) in viewController.m in viewDidLoad
NSError *error = nil;
self.theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
4.) - (IBAction)homeBtnTpd {
[self.theAudio play];
}
You should set Applications does not run in background to NO

iOS How to play alert sound in speaker when recording

I want to manually trigger to play some alert sound during recording audio, and I want the alert sound be recorded. So I want the alert play loudly in speaker instead of Receiver during recording audio.
I use AVAudioRecorder to record audio and use AVAudioPlayer to play the alert sound.
Code for recorder
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *sessionError;
[session setCategory:AVAudioSessionCategoryRecord error:&sessionError];
if(session == nil)
NSLog(#"Error creating session: %#", [sessionError description]);
else
[session setActive:YES error:nil];
recorder = [[AVAudioRecorder alloc] initWithURL:_recordedFile settings:recordSettings error:nil];
[recorder prepareToRecord];
[recorder record];
Code for player
AVAudioSession *session = [AVAudioSession sharedInstance];
// session.outputDataSources
NSError *sessionError;
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
// use the louder speaker
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
sizeof (audioRouteOverride),&audioRouteOverride);
if(session == nil)
NSLog(#"Error creating session: %#", [sessionError description]);
else
[session setActive:YES error:nil];
NSError *error;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.filePath error:&error];
player.delegate =self;
player.volume = 1.0;
player.numberOfLoops = 0;
self.timeDuration = player.duration;
If I stop the recording, and manually trigger the play alert, it plays in speaker.
But during recording, when I manually trigger the play alert, nothing happens.
Is there anything wrong here? Or Is it possible to play sound in speaker when recording?
Just change category as below thats all
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&err];

how to keep an avaudioplayer playing in device(iPhone) locked condition?

I am using AVAudioPlayer in my application.my problem is, it is not playing when the device gets locked.
Follow the steps in the image below. It should work.
I use this code:
- (void)playAudio:(NSString *)path {
NSError *error;
NSURL *audioURL = [NSURL fileURLWithPath:path];
self.notificationPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:audioURL error:&error];
self.notificationPlayer.delegate = self;
AVAudioSession* audioSession = [AVAudioSession sharedInstance];
NSError *errorSession = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil];
[audioSession setActive:NO error:&errorSession];
[self.notificationPlayer prepareToPlay];
[self.notificationPlayer setVolume:1.0];
[self.notificationPlayer play];
if (error) {
NSLog(#"error %#",[error localizedDescription]);
}
NSLog(#"Should play music");
}
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[player stop];
[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
}
Reference Link
Hope this code useful for you.

AVAudioPlayer doesn't play audio in iPhone 5 when locked

Using AVAudioPlayer I'm trying to play sounds while the iphone player is playing. Also when device is locked.
The thing is, that in iPhone 4s ios 7 - works fine.
But on iPhone 5 with 6 and 7 ios nothing happens.
In the -Info.plist in Required background modes I wrote
App plays audio or streams audio/video using AirPlay
in Player.h implemented:
#property (nonatomic, strong) AVAudioPlayer *notificationPlayer;
<AVAudioPlayerDelegate, AVAudioSessionDelegate> with
#import <AVFoundation/AVFoundation.h> included
Also in Player.m
//this is called on viewDidLoad
-(void) prepareSound{
[[AVAudioSession sharedInstance] setDelegate:self];
}
//overriden function
- (void)playAudio:(NSString *)path{
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryAmbient
withOptions: AVAudioSessionCategoryOptionDuckOthers
error: nil];
NSError *error;
NSURL *audioURL = [NSURL fileURLWithPath:path];
self.notificationPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:audioURL error:&error];
self.notificationPlayer.delegate = self;
[self.notificationPlayer prepareToPlay];
[self.notificationPlayer setVolume:1.0];
[self.notificationPlayer play];
if (error) {
NSLog(#"error %#",[error localizedDescription]);
}
}
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[player stop];
[[AVAudioSession sharedInstance] setActive:NO withOptions:0 error:nil];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient
withOptions: 0
error: nil];
[[AVAudioSession sharedInstance] setActive:YES withOptions: 0 error:nil];
}
//Call from here
-(void) customMethod{
[self playAudio:[[NSBundle mainBundle] pathForResource:#"3" ofType:#"wav"]];
}
Regards.
Another Really important thing to note while playing sounds in background is whether or not you have permission to the file. If you are playing a bundle file, you have permission, and presumably some file streamed from the internet, but if you've downloaded media into the documents directory, then you must set permissions appropriately, especially if your application natively locks files.
This tends to match with what many people see as a symptom where the file will continue to play for a couple of seconds, 5-15, then stop. If you're listening for the finished method, you'll see an error flag. Why: AVAudioPlayer won't load the entirety of your audio file into memory when you first play it.
Example:
NSURL url = [NSURL URLWithString:#""];
NSError *error = nil;
[[NSFileManager defaultManager] setAttributes:#{NSFileProtectionKey :
NSFileProtectionCompleteUntilFirstUserAuthentication} ofItemAtPath:[url path] error:&error];
Your options are as follows:
NSFileProtectionComplete;
NSFileProtectionCompleteUnlessOpen;
NSFileProtectionCompleteUntilFirstUserAuthentication;
NSFileProtectionNone;
I should use the following code
- (void)playAudio:(NSString *)path {
NSError *error;
NSURL *audioURL = [NSURL fileURLWithPath:path];
self.notificationPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:audioURL error:&error];
self.notificationPlayer.delegate = self;
AVAudioSession* audioSession = [AVAudioSession sharedInstance];
NSError *errorSession = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:nil];
[audioSession setActive:NO error:&errorSession];
[self.notificationPlayer prepareToPlay];
[self.notificationPlayer setVolume:1.0];
[self.notificationPlayer play];
if (error) {
NSLog(#"error %#",[error localizedDescription]);
}
NSLog(#"Should play music");
}
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[player stop];
[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
}

Resources