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

你。 提交于 2019-11-26 14:30:44

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.

dhaval rupani

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.

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.

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

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

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)")
                    }
            });
Evgenii Melnik

Also you can use this code:

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

AVAudioSession *backgroundMusic = [AVAudioSession sharedInstance];

[backgroundMusic setCategory:AVAudioSessionCategoryPlayback error:NULL];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!