【问题标题】:Get System Volume iOS获取系统音量 iOS
【发布时间】:2011-11-07 11:22:18
【问题描述】:

我的情况很简单: 我需要播放警告信号并确保用户能听到,所以我想检查系统音量。

如何知道当前系统的音量是多少?

【问题讨论】:

    标签: ios objective-c swift audio volume


    【解决方案1】:

    Swift 更新

    let vol = AVAudioSession.sharedInstance().outputVolume
    

    音频会话可以提供输出音量(iOS >= 6.0)。

    float vol = [[AVAudioSession sharedInstance] outputVolume];
    NSLog(@"output volume: %1.2f dB", 20.f*log10f(vol+FLT_MIN));
    

    【讨论】:

    • 我在 iOS 11 中使用今天的扩展 - 有时它不起作用
    • stackoverflow.com/questions/24872409/… - 尝试播放音频然后检查。有同样的问题,为我工作。
    • 请务必先执行AVAudioSession.sharedInstance().setActive(true),否则更改音量时此值不会更新
    • 有点小问题:返回的值不是可以像这样直接转换为分贝的比率/增益。该值直接反映了音量指标的位置,Apple 并未宣传它与实际增益或分贝值的关系。很可能它是映射到分贝范围的比例,但任何人都可以猜测比例是多少。
    【解决方案2】:

    斯威夫特 3.1

    let audioSession = AVAudioSession.sharedInstance()
    var volume: Float?
    do {
        try audioSession.setActive(true)
        volume = audioSession.outputVolume
    } catch {
        print("Error Setting Up Audio Session")
    }
    

    audioSession.setActive(true) - 重要

    【讨论】:

    • 你能分享一下为什么 setActive(true) 很重要吗?
    【解决方案3】:

    试试这个:

    MPMusicPlayerController *iPod = [MPMusicPlayerController iPodMusicPlayer];
    float volumeLevel = iPod.volume;
    

    您需要导入 MediaPlayer 框架。

    【讨论】:

    • 已弃用,请改用 [[AVAudioSession sharedInstance] outputVolume]。
    【解决方案4】:

    这很好用:

    Float32 volume;
    UInt32 dataSize = sizeof(Float32);
    
    AudioSessionGetProperty (
                         kAudioSessionProperty_CurrentHardwareOutputVolume,
                         &dataSize,
                         &volume
                         );
    

    【讨论】:

    • 对我来说更好!现在我可以放弃 MediaPlayer 框架了。
    • 这在 iOS 7 中已被弃用 - 有人知道新方法吗?
    【解决方案5】:

    对于 Swift 2

    let volume = AVAudioSession.sharedInstance().outputVolume   
    print("Output volume: \(volume)")
    

    【讨论】:

    • 我们还需要audioSession.setActive(true)
    【解决方案6】:

    您可以使用默认系统的音量视图并添加到您需要的任何位置。就我而言,我需要在我自己的音乐播放器中使用它。这很容易而且没有麻烦。只需添加视图,一切就完成了。这在 Apple 的 MPVolume Class Reference 中进行了解释。

    mpVolumeViewParentView.backgroundColor = [UIColor clearColor];
    MPVolumeView *myVolumeView =
    [[MPVolumeView alloc] initWithFrame: mpVolumeViewParentView.bounds];
    [mpVolumeViewParentView addSubview: myVolumeView];
    [myVolumeView release];
    

    【讨论】:

    • 问题不是如何为用户提供改变音量的方式,而是如何检测音量是否足够高。这个答案有什么帮助?
    • True 与问题不是特别相关,但在如何调整系统音量的更大范围内仍然有用。
    【解决方案7】:

    我已经准备了一个带有静态方法的类来处理大量的 ios 设备。让我与你分享:)

    import AVFoundation
    class HeadPhoneDetectHelper {
    class func isHeadPhoneConnected() -> Bool
    {
        do{
            let audioSession = AVAudioSession.sharedInstance()
            try audioSession.setActive(true)
            let currentRoute = audioSession.currentRoute
            let headPhonePortDescriptionArray = currentRoute.outputs.filter{$0.portType == AVAudioSessionPortHeadphones}
            let isHeadPhoneConnected = headPhonePortDescriptionArray.count != 0
            return isHeadPhoneConnected
        }catch{
            print("Error while checking head phone connection : \(error)")
        }
        return false
    }
    
    class func isVolumeLevelAppropriate() -> Bool
    {
        let minimumVolumeLevelToAccept = 100
        let currentVolumeLevel = HeadPhoneDetectHelper.getVolumeLevelAsPercentage()
        let isVolumeLevelAppropriate = currentVolumeLevel >= minimumVolumeLevelToAccept
        return isVolumeLevelAppropriate
    }
    
    class func getVolumeLevelAsPercentage() -> Int
    {
        do{
            let audioSession = AVAudioSession.sharedInstance()
            try audioSession.setActive(true)
            let audioVolume =  audioSession.outputVolume
            let audioVolumePercentage = audioVolume * 100
            return Int(audioVolumePercentage)
        }catch{
            print("Error while getting volume level \(error)")
        }
        return 0
    }
    }
    

    【讨论】:

      【解决方案8】:

      Swift 2.2,确保导入 MediaPlayer

      private func setupVolumeListener()
      {
          let frameView:CGRect = CGRectMake(0, 0, 0, 0)
          let volumeView = MPVolumeView(frame: frameView)
          //self.window?.addSubview(volumeView) //use in app delegate
         self.view.addSubview(volumeView)  //use in a view controller
      
      
          NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(volumeChanged(_:)), name: "AVSystemController_SystemVolumeDidChangeNotification", object: nil)
      }//eom
      
      
      
      func volumeChanged(notification:NSNotification)
      {
          let volume = notification.userInfo!["AVSystemController_AudioVolumeNotificationParameter"]
          let category = notification.userInfo!["AVSystemController_AudioCategoryNotificationParameter"]
          let reason = notification.userInfo!["AVSystemController_AudioVolumeChangeReasonNotificationParameter"]
      
          print("volume:      \(volume!)")
          print("category:    \(category!)")
          print("reason:      \(reason!)")
          print("\n")
      }//eom
      

      【讨论】:

        猜你喜欢
        • 2011-05-18
        • 2019-12-13
        • 1970-01-01
        • 1970-01-01
        • 2011-06-06
        • 1970-01-01
        • 1970-01-01
        • 2021-04-10
        • 1970-01-01
        相关资源
        最近更新 更多