Play music in background when home button is press - ios

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

Related

Why does background music stops when playing an AVPlayer/AVQueuePlayer without setting AudioSession active?

When I play an m3u8 on an AVQueuePlayer with setting the player mute, the music from another app in the background stops. I did not set AudioSession category and session as shown in the sample code.
Does the AVQueuePlayer set AudioSession category and session by default when I do replaceCurrentItemWithPlayerItem? Or how does the background music stops?
#import "ViewController.h"
#import AVFoundation;
#interface ViewController ()
#property (nonatomic, nonnull) AVQueuePlayer * player;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.player = [[AVQueuePlayer alloc] init];
[self.player setMuted:YES];
NSURL *URL = [NSURL URLWithString:#"https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8"];
// [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
// [[AVAudioSession sharedInstance] setActive:NO error:nil];
AVPlayerItem * item = [AVPlayerItem playerItemWithURL:URL];
[self.player replaceCurrentItemWithPlayerItem:item];
[self.player play];
// Do any additional setup after loading the view.
}
#end
you should use [AVAudioSession setCategory:withOptions:error:] method https://developer.apple.com/documentation/avfoundation/avaudiosession/1616442-setcategory?language=objc
make sure to use AVAudioSessionCategoryOptionMixWithOthers option.
for example:
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback withOptions: AVAudioSessionCategoryOptionMixWithOthers error: nil];
[[AVAudioSession sharedInstance] setActive:NO error:nil];

avplayer not playing audio in video which is captured through device camera in IOS objective-C

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:)

How to programmatically mute video

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

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