AVAudioPlayer在应用程序进入后台后停止返回正确的currentTime。
创始人
2024-11-12 21:30:42
0

在应用程序进入后台后,AVAudioPlayer会被暂停,因此获取currentTime时可能会返回不正确的值。要解决这个问题,可以在应用程序进入后台之前保存当前的currentTime,并在应用程序返回前台时恢复它。

以下是一个示例代码:

import AVFoundation
import UIKit

class ViewController: UIViewController {
    var audioPlayer: AVAudioPlayer?
    var currentTime: TimeInterval = 0.0 // 保存当前的currentTime

    override func viewDidLoad() {
        super.viewDidLoad()

        // 初始化AVAudioPlayer
        guard let filePath = Bundle.main.path(forResource: "audio", ofType: "mp3") else {
            return
        }
        let url = URL(fileURLWithPath: filePath)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.prepareToPlay()
        } catch {
            print("Failed to initialize AVAudioPlayer: \(error)")
        }

        // 注册应用程序进入后台和返回前台的通知
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }

    @objc func applicationDidEnterBackground() {
        // 保存当前的currentTime
        currentTime = audioPlayer?.currentTime ?? 0.0
        audioPlayer?.pause()
    }

    @objc func applicationWillEnterForeground() {
        // 恢复之前保存的currentTime并继续播放音频
        audioPlayer?.currentTime = currentTime
        audioPlayer?.play()
    }
}

在这个示例中,我们使用AVAudioPlayer来播放一个名为"audio.mp3"的音频文件。当应用程序进入后台时,我们保存当前的currentTime,并在应用程序返回前台时恢复它并继续播放音频。

相关内容

热门资讯

必备科技!拱趴大菠萝有挂吗,德... 您好,拱趴大菠萝有挂吗这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
一分钟了解!德州私人局怎么透视... 一分钟了解!德州私人局怎么透视,pokemmo手机脚本,2025新版教程(有挂透视);原来确实真的有...
一分钟揭秘!哈糖大菠萝开挂,h... 一分钟揭秘!哈糖大菠萝开挂,hhpoker作弊码,必胜教程(有挂技巧);1.哈糖大菠萝开挂 ai辅助...
今日公布!哈糖大菠萝可以开挂吗... 今日公布!哈糖大菠萝可以开挂吗,wepoker怎么看底牌,详细教程(有挂方法)是由北京得哈糖大菠萝可...
玩家攻略!哈糖大菠萝有挂吗,佛... 玩家攻略!哈糖大菠萝有挂吗,佛手在线大菠萝智能辅助器,2025新版技巧(有挂软件);1分钟了解详细教...
最新技巧!模拟器打开hhpok... 最新技巧!模拟器打开hhpoker,wpk官网下载链接,我来教教你(有挂方法);模拟器打开hhpok...
一分钟揭秘!pokemmo脚本... 一分钟揭秘!pokemmo脚本,hhpoker脚本,微扑克教程(有挂技巧);建议优先通过pokemm...
安装程序教程!德普之星辅助器怎... 安装程序教程!德普之星辅助器怎么用,wepoker辅助器怎么弄,微扑克教程(有挂透明)1、不需要AI...
记者发布!wepoker黑侠辅... 1、记者发布!wepoker黑侠辅助器正版下载,wejoker黑侠辅助器,高科技教程(有挂教程)。2...
实测教程!wepoker插件辅... 实测教程!wepoker插件辅助,wepoker有辅助功能吗,软件教程(有挂攻略)关于wepoker...