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.
Related
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!
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 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
I have these code and both method call are SUCCESS.
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory: AVAudioSessionCategoryPlayAndRecord error: NULL];
[audioSession setActive: YES error: NULL];
And these code to start recording:
[self.recorder prepareToRecord];
[self.recorder recordForDuration: 60];
I have a timer function to update meters
- (void)updateMeters
{
[self.recorder updateMeters];
float peakPower = [self.recorder averagePowerForChannel: 0];
double ALPHA = 0.05;
double peakPowerForChannel = pow(10, (ALPHA * peakPower));
self.recordView.progress = peakPowerForChannel;
NSLog(#"%f", peakPower);
}
But I do not know why peakPower is always 160. I have another demo(from web) can work well, but I can not find any difference between them.
Just try to set:
recorder.meteringEnabled = YES;
Set the category to AVAudioSessionCategoryPlayAndRecord and check
NSError *error;
[[AVAudioSession sharedInstance]
setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
if (error) {
NSLog(#"Error description: %#", [error description]);
}
It is strange that [audioSession setCategory: AVAudioSessionCategoryPlayAndRecord error: &err] and [[AVAudioRecorder alloc] initWithURL: [NSURL fileURLWithPath: self.recordPath] settings: recordSetting error: NULL] must in the same function...It is the answer of this question.
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];
}