I try to make an audio/video call with openTok with the possibility to change de output speaker. I want to be set on ear speaker for default and i use that code.
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
self.audioSpeakerButton.selected =true;
First time i play a ringtone with AVAudioPlayer with code below:
audioPLayer =[[AVAudioPlayer alloc]initWithContentsOfURL:pewPewURL fileTypeHint:#"mp3" error:nil];
audioPLayer.numberOfLoops=-1;
[audioPLayer prepareToPlay];
[audioPLayer play];
The sound comes from ear speaker which is good.
After when the second user is connected i stop the audioPlayer but the sound it is comes from loudspeaker which is bad.
- (void)subscriberDidConnectToStream:(OTSubscriberKit *)subscriber
{
[audioPLayer pause];
[audioPLayer stop];
audioPLayer = nil;
}
I use that button action for change output speaker but nothing is changed.
-(void)audioSpeakerButtonAction{
if (![self.audioSpeakerButton isSelected]) {
NSError *error = nil;
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error];
self.audioSpeakerButton.selected = YES;
} else {
NSError *error = nil;overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
self.audioSpeakerButton.selected = NO;
}
}
I will appreciate any help. Thanks in advance!
Related
In my situation, when I pressed play button sound comes low at starting and after some time it comes louder for speaker. In my project too many audio files are available. When I pressed first then it starts with low sound and when I pressed second and third it starts and all played in loud sound from speaker. Every time when I pressed play button, it executed below code.
- (SWYAudioBoardPlayer*) initWithMediaKey:(NSString *) mediaKey{
self.session = [AVAudioSession sharedInstance]; // Object declare above
NSError *error = nil;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:#"audioUrl" error:&error];
[audioPlayer setDelegate:self];
isPause = false;
audioPlayer.volume = 1.0;
defaultAVAudioSessionCategory = [self.session category]; // Object declare above
[self loudSpeakerOn:true];
return [self init]; }
- (void) loudSpeakerOn:(BOOL)isLoudSpeaker{
[self.session setActive:NO error:nil];
BOOL success;
NSError* error;
success = [self.session overrideOutputAudioPort:isLoudSpeaker?AVAudioSessionPortOverrideSpeaker:AVAudioSessionPortOverrideNone error:&error];
if (!success) NSLog(#"AVAudioSession error setting category:%#",error);
[self.session setActive:YES error:nil];}
I am capturing the video from the device camera and than storing that video into the device local memory and than in the next screen I am playing that video using AVPlayer but I am not getting sound from video.Here is code of video playback
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
_avPlayer=[[AVPlayer alloc]initWithURL:url]; //URL of my recorded video
_avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:_avPlayer];
[_avPlayerLayer setFrame:CGRectMake(0, 0, self.videoview.frame.size.width, self.videoview.frame.size.height)];
[_avPlayerLayer setBackgroundColor:[[UIColor blackColor]CGColor]];
_avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.pictureview.layer addSublayer:_avPlayerLayer];
[_avPlayer seekToTime:kCMTimeZero];
_avPlayer = [self rotateVideoPlayer:_avPlayer withDegrees:0.0];
_avPlayer.volume = 1.0;
[_avPlayer play];
Note:- Video has sound because After preview, I am uploading the video on server and in that I can hear a sound from recorded video.
I am using AVCaptureSession to record video and has added AVMediaTypeVideo and AVMediaTypeAudio as AVCaptureDevice. So will it make any problem at a time of playback. Before Playback I am removing AVCaptureDevice devices from the AVCaptureSession and than playing the captured video.
I got same issue a time ago, and adding this code to AppDelegate method helped me:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSError *err;
AVAudioSession *session = [AVAudioSession sharedInstance];
bool success = [session setCategory:AVAudioSessionCategoryPlayback
error:&err];
if (!success) {
DLog(#"error changing audio mode %#", err);
[session setCategory:AVAudioSessionCategoryPlayback
error:&err];
if (err) {
DLog(#"error changing audio mode %#", err);
}
}
}
Also if it doesn't help, try to turn off the "mute" button on your device.
Also check error description if it does exist.
UPDATE:
Do you initialize your audio input something like this?
AVCaptureDevice *audioDevice = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
AVCaptureDeviceInput *audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
if (error)
{
NSLog(#"%#", error);
}
if ([session canAddInput:audioDeviceInput])
{
[session addInput:audioDeviceInput];
}
You can easily play video with MPMoviePlayerController. In one my project I am playing like,
self.videoController = [[MPMoviePlayerController alloc] init];
[self.videoController setContentURL:videourl];
[self.videoController.view setFrame:CGRectMake (0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[self.view addSubview:self.videoController.view];
UIButton *closeButton = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-60, 20, 60, 30)];
[closeButton addTarget:self action:#selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
[closeButton setTitle:#"Cancel" forState:UIControlStateNormal];
[self.videoController.view addSubview:closeButton];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(videoPlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.videoController];
[self.videoController play];
I am adding close button and observer, you not need to do that if not required.
And don't forget to import <MediaPlayer/MediaPlayer.h>
Update :
audioSession = [AVAudioSession sharedInstance];
NSError *err;
NSError *error;
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &err];
if (err) {
NSLog(#"ERROR occured %#",[err localizedDescription]);
}
[audioSession setActive:YES error: &error];
[audioSession setActive:NO error:nil];
// [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
error:nil];
[audioSession setActive:YES error:nil];
audioPlayer = nil;
//NSError *error;
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:self.audioRecorder1.url
error:&error];
// audioPlayer.volume = 1.0;
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPlayer play];
You use avplayer instead of audio player! main concern is session!
Hope this will help:)
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];
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.
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];
}