騰訊直播SDK接入及封裝(一)之錄屏直播

哇哈爽發表於2024-11-18

1.省略整合SDK環節,具體的整合以官方為主,這裡只是快速接入的參考;

2.獲取系統相機、麥克風、螢幕錄製等的許可權,這裡以麥克風為例:

func checkMicroPermission() -> Bool {
    let authStatus = AVCaptureDevice.authorizationStatus(for: .audio)
    switch (authStatus) {
    case .authorized:
        //授權
        return true
    case .notDetermined, .restricted, .denied:
        return false
        default:
        return false
    }
}

根據使用者設定詢問是否授權

if !checkMicroPermission() {
    AVCaptureDevice.requestAccess(for: .audio) { granted in
        if granted {
            DispatchQueue.main.async {
                //授權成功後進行後續操作
            }
        }
    }
}

3.直播封裝

1.建立一個單例保持直播一直在運作
class LiveManager: NSObject {
    static let shared = LiveManager()
    //防止外界init
    private override init() {
        
    }
}

2.建立直播推流及直播拉流
private var livePusher: V2TXLivePusher?
private var livePlayer: V2TXLivePlayer = {
    let txPlayer = V2TXLivePlayer()
    return txPlayer
}()

3.開啟錄屏直播(注:在此之前從後端拿到推流地址,pushUrl:推流地址)
func startRecord(_ pushUrl: String) {
    if self.livePusher != nil {
        self.livePusher?.stopScreenCapture()
        self.livePusher?.stopPush()
    }
    //開啟錄屏
    TRTCBroadcastExtensionLauncher.launch()
    //推流,liveMode選擇RTC,因為後面要接入連麥功能的時候只能用這個,如果選RTMP連麥混流會有問題
    let pusher = V2TXLivePusher(liveMode: .RTC)
    //註冊觀察者
    pusher?.setObserver(self)
    self.livePusher = pusher
    //這裡可以根據文件來填
    pusher?.startScreenCapture("xx.xx.xx")
    pusher?.startMicrophone()
    let videoParam = V2TXLiveVideoEncoderParam()
    //這個resolution640x360根據自己的情況來,並不是越高越好
    videoParam.videoResolution = .resolution640x360
    //橫豎屏模式,我們這邊是錄製遊戲橫屏,根據自己的情況設定
    videoParam.videoResolutionMode = .landscape
    pusher?.setVideoQuality(videoParam)
    pusher?.setAudioQuality(.default)
    let code = pusher?.startPush(pushUrl)
    if code != V2TXLiveCode.TXLIVE_OK {
        //這裡是失敗的情況
        pusher?.stopMicrophone()
        pusher?.stopScreenCapture()
    }
}

然後是關閉直播

func stopRecord() {
    if self.livePusher != nil {
        self.livePusher?.stopScreenCapture()
        self.livePusher?.stopPush()
    }
}

然後是客戶端進行拉流操作

相關文章