admin管理员组

文章数量:1122846

I have an AVAudioSession (the sharedInstance() one), I enable it and observe the outputVolume of it. That works, it correctly reports the device's volume. After the first .setActive(true) the .outputVolume is correct.

However, after I disable the audio session (.setActive(false)) and enable it once again, calling .outputVolume gives me the last volume before deactivating the session and not the current device's volume. After I change the volume using physical buttons or Control Center, I get the update in observer with the correct volume. But I need to check the actual device volume after re-activating the audio session.

I want to get the correct device's volume after activating audio session for the second and consecutive times.

Disabling and enabling the audio session is crucial to how my application works.

I've tested this behavior with my colleagues. The problem is present on both iOS 18.0.1 and iOS 18.1. On two iOS 17.6.1 devices, the outputVolume was reporting a correct value right after calling .setActive(true) for the second and nth time.


Below is a minimum reproducible example. Steps to reproduce:

  1. Enable audio session. The volume was initialized with the correct value.
  2. Click on the volume buttons. The text is updated correctly.
  3. Disable audio session. Change the volume using physical buttons or the Control Center.
  4. Enable audio session. The volume (fetched from .outputVolume) has not been updated. It's as it was right before deactivation.

I'm not iOS/Swift developer so the code itself may be suboptimal.

import AVFoundation
import SwiftUI

@main
struct AudioSessionTestApp: App {
    @State private var active = false
    @State private var volume = 0.0
    @State private var volumeObservation: NSKeyValueObservation?

    var body: some Scene {
        WindowGroup {
            ZStack {
                Color.red.interpolateTo(
                    color: Color.green,
                    fraction: volume
                ).ignoresSafeArea()

                VStack(spacing: 24) {
                    Text("Audio session active: \(active)")
                    Button("Toggle") {
                        active = !active
                        if active {
                            enableSession()
                        } else {
                            disableSession()
                        }
                    }.buttonStyle(.borderedProminent)
                    Text("Session volume: \(volume)")
                }
                .padding()
            }
        }
    }

    func enableSession() {
        let session = AVAudioSession.sharedInstance()

        try? session.setActive(true)
        try? session.setCategory(.playback)

        volume = Double(session.outputVolume)
        volumeObservation = session.observe(\.outputVolume) { session, _ in
            NSLog("Observed volume change to \(session.outputVolume)")
            volume = Double(session.outputVolume)
        }
    }

    func disableSession() {
        volumeObservation?.invalidate()
        volumeObservation = nil

        let session = AVAudioSession.sharedInstance()
        try? session.setActive(false)
    }
}

// 
extension Color {
    var components: (r: Double, g: Double, b: Double, o: Double)? {
        let uiColor: UIColor

        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var o: CGFloat = 0

        if description.contains("NamedColor") {
            let lowerBound = description.range(of: "name: \"")!.upperBound
            let upperBound = description.range(of: "\", bundle")!.lowerBound
            let assetsName = String(description[lowerBound ..< upperBound])

            uiColor = UIColor(named: assetsName)!
        } else {
            uiColor = UIColor(self)
        }

        guard uiColor.getRed(&r, green: &g, blue: &b, alpha: &o) else { return nil }

        return (Double(r), Double(g), Double(b), Double(o))
    }

    func interpolateTo(color: Color, fraction: Double) -> Color {
        let s = components!
        let t = colorponents!

        let r: Double = s.r + (t.r - s.r) * fraction
        let g: Double = s.g + (t.g - s.g) * fraction
        let b: Double = s.b + (t.b - s.b) * fraction
        let o: Double = s.o + (t.o - s.o) * fraction

        return Color(red: r, green: g, blue: b, opacity: o)
    }
}

本文标签: iosAVAudioSession outputVolume not correct after deactivating and activating the sessionStack Overflow