You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

后台线程调用AVFoundation导致SwiftUI动画卡顿问题求助

AVFoundation操作导致SwiftUI动画卡顿问题

我开发的应用存在动画卡顿问题,已将问题简化为以下复现代码:

struct ContentView: View {
    var body: some View {
        ZStack {
            AnimatingCircle()
            Button("Trigger animation stutter") {
                Task {
                    await MyActor().go()
                }
            }
        }
    }
}

private struct AnimatingCircle: View {
    @State var shouldAnimate = false
    var body: some View {
        Circle()
            .fill(.red)
            .animation(.easeInOut.repeatForever(autoreverses: true)) {
                $0.scaleEffect(shouldAnimate ? 1.5 : 0.5)
            }
            .onAppear {
                shouldAnimate = true
            }
    }
}

final actor MyActor {
    let captureSession = AVCaptureSession()

    func go() {
        let microphone = AVCaptureDevice.DiscoverySession(
            deviceTypes: [.microphone],
            mediaType: .audio,
            position: .unspecified
        ).devices.first!
        captureSession.addInput(try! AVCaptureDeviceInput(device: microphone))
        captureSession.addOutput(AVCaptureAudioDataOutput())
        captureSession.startRunning()
    }
}

点击按钮时,圆形动画会出现明显卡顿。我已确认所有AVFoundation调用都在后台线程执行,但仍不知如何解决该问题。

我有两个疑问:

  • AVFoundation代码为何会干扰动画?是否意味着AVFoundation内部有逻辑会派回到主线程?
  • 有哪些可行的解决思路?

动画卡顿效果如下:
动画卡顿效果

更新1

感谢大家对Task和Actor使用方式的关注,但这并非问题根源。以下代码同样会触发该bug:

Button("Trigger animation stutter") {
    DispatchQueue.global().async {
        go()
    }
}

func go() {
    let captureSession = AVCaptureSession()
    let microphone = AVCaptureDevice.DiscoverySession(
        deviceTypes: [.microphone],
        mediaType: .audio,
        position: .unspecified
    ).devices.first!
    captureSession.addInput(try! AVCaptureDeviceInput(device: microphone))
    captureSession.addOutput(AVCaptureAudioDataOutput())
    captureSession.startRunning()
}

内容的提问来源于stack exchange,提问作者Lou Zell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 00:25:56