播放无声音乐让后台一直运行

我们项目要求我们是每隔一个小时上传一次地理位置,试了好几种方法都不成功,只能选择后台循环播放音乐达到后台持续运行.(我是企业账号开发的,不清楚App Store上传上去会不会有问题)

1.首先用到音频,需要 import MediaPlayer

2. 音频播放代码

do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print(error)

  }
        let path = NSBundle.mainBundle().pathForResource("voice", ofType: "wav") //音频文件
        
        let pathURL=NSURL(fileURLWithPath: path!)
        
        do {
            
            audioPlayer = try AVAudioPlayer(contentsOfURL: pathURL)
            audioPlayer?.prepareToPlay()
            audioPlayer?.numberOfLoops = -1 //循环
            audioPlayer?.volume = 0.0//无声
            audioPlayer?.play()
            
            //UIApplication.sharedApplication().beginReceivingRemoteControlEvents()  锁屏的时候显示用,这里不用显示
            
        } catch {
            audioPlayer = nil
        }
          

//来电话等中断音频播放时的处理

NSNotificationCenter.defaultCenter().addObserver(self, selector:

#selector(ViewController.breakAudioSessionEvent(_:)),name: AVAudioSessionInterruptionNotification, object: nil)

3.音频中断处理方法

  func breakAudioSessionEvent(sender:NSNotification){
       
        //音乐被中断,重新播放
        
        do {
            
            audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath:

NSBundle.mainBundle().pathForResource("voice", ofType: "wav")!))
            audioPlayer?.prepareToPlay()
            audioPlayer?.numberOfLoops = -1 //循环
            audioPlayer?.volume = 0.0//无声
            audioPlayer?.play()
            
        } catch {
            audioPlayer = nil
            print(error)
        }
    }

4.这样测试下来,几个小时还继续后台运行,位置也一直上传着



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值