How to handle background audio playing while iOS device is locked or on another application?
Asked Answered
P

6

28

Designing a generative music system for iOS, using OpenFrameworks, I'd need to provide a mode in which the user could listen the music produced by the application when:

  • the device is locked
  • the user uses another application

Some applications like BLOOM, or alarm clock, works like that and propose to users a switch to enable/disable this feature.

Any tips for that ?

Personify answered 3/5, 2012 at 10:6 Comment(0)
A
36

Playing Background Audio

An app that plays or records audio continuously (even while the app is running in the background) can register to perform those tasks in the background. You enable audio support from the Background modes section of the Capabilities tab in your Xcode project. (You can also enable this support by including the UIBackgroundModes key with the audio value in your app’s Info.plist file.) Apps that play audio content in the background must play audible content and not silence.

Apple reference "Playing and Recording Background Audio"

Ensuring That Audio Continues When the Screen Locks

For enabling/disabling this feature I found Activating and Deactivating Your Audio Session, I haven't tried it myself, but it looks like what you need.

Audryaudrye answered 3/5, 2012 at 13:33 Comment(8)
Hi Danich and thanks a lot for your answer. Is there a way to change it at run time ?Personify
I opened another thread for this particular point: #10504932Personify
Sorry, didn't noticed your question about enable/disable. I think new thread is not a good idea. Updated my answer. Accept, if you think it's useful.Audryaudrye
let's do that. testing it right now. I fixed a typo on your last link.Personify
The second link in this answer is 404, I think it should be pointing here: developer.apple.com/library/ios/qa/qa1626/_index.htmlUlibarri
Your second link is golden! Thanks so much.Dolly
It seems like AVAudioSessionCategoryPlayback is basically a must as well, UIBackgroundModes set to audio is NOT not enough. At least AVAudioSessionCategoryAmbient, SoloAmbient etc does NOT work as it will always silence sound - the app might still run in the background but sound will be stopped...Thompkins
The first link seems to be outdated, the content doesn’t matchLifesaver
C
29

You need to make couple of changes in plist file.

i.e. 1) Set Required background mode to App plays audio

2) set Application does not run in background to NO.

 NSError *setCategoryErr = nil;
 NSError *activationErr  = nil;
 [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
 [[AVAudioSession sharedInstance] setActive:YES error:&activationErr];

Then, you need to write these much code in AppDelegate

Now, you can easily run audio while phone screen locks or goes in background.

Colonel answered 1/2, 2013 at 7:21 Comment(2)
"Application does not run in background" should be set to "NO"Ruby
This is great, thanks. I also needed to set Capabilities > Background Modes > Audio & AirPlayOversweet
C
3

Make the following changes in xCode project settings as well as in code.

step 1) Select your project file in the Navigator of Xcode. Then, from the Capabilities section, switch on the Background Modes subsection. After the list of background modes is given to you, tick on the Audio & Airplay switch.

stp 2) Use following swift code, basically you need to set audio session for your app.

var audioPlayer : AVAudioPlayer!

@IBAction func playButtonClicked(sender : AnyObject){

    let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    dispatch_async(dispatchQueue, {

        if let data = NSData(contentsOfFile: self.audioFilePath())
        {
            do{
                let session = AVAudioSession.sharedInstance()

                try session.setCategory(AVAudioSessionCategoryPlayback)
                try session.setActive(true)

                self.audioPlayer = try AVAudioPlayer(data: data)
                //self.audioPlayer.delegate = self
                self.audioPlayer.prepareToPlay()
                self.audioPlayer.play()
            }
            catch{
                print("\(error)")
            }
        }
    });
}

func audioFilePath() -> String{

    let filePath = NSBundle.mainBundle().pathForResource("mySong", ofType: "mp3")!
    return filePath
}

This audio playback session will be play your application playback, even if app is in background or phone is in silent mode or device is locked.

Constipation answered 27/10, 2015 at 18:2 Comment(0)
L
1

Look at on this tutorial. It has some of background services example

http://www.raywenderlich.com/29948/backgrounding-for-ios

Longley answered 18/11, 2015 at 7:43 Comment(0)
C
0

You need to make couple of changes in plist file.

1) Set Required background mode to App plays audio

2) set Application does not run in background to NO.

let dispatchQueue = DispatchQueue.global()
            dispatchQueue.async(execute: {
                    do{
                        let session = AVAudioSession.sharedInstance()

                        try session.setCategory(AVAudioSessionCategoryPlayback)
                        try session.setActive(true)

                        self.isObjectAllocate = true
                        if self.isPlayed == false{
                            self.playSound(soundName: "http://radio.zahraun.com:8000/live.m3u")
                            self.isPlayed = true
                            self.btnPlayAudio.setImage(#imageLiteral(resourceName: "pause") , for: .normal)

                        }else{
                            self.audioPlayer.pause()
                            self.isPlayed = false
                            self.btnPlayAudio.setImage(#imageLiteral(resourceName: "audioPlay"), for: .normal)
                        }
                    }
                    catch{
                        print("\(error)")
                    }
            });
Commemorate answered 17/3, 2017 at 8:19 Comment(0)
O
-2

Also you can use this code:

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:NULL];

AVAudioSession *backgroundMusic = [AVAudioSession sharedInstance];

[backgroundMusic setCategory:AVAudioSessionCategoryPlayback error:NULL];
Obstruction answered 23/5, 2013 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.