Get System Volume iOS

后端 未结 8 2224
死守一世寂寞
死守一世寂寞 2020-11-27 05:02

My case is simple: I need to play a warning signal and want to make sure the user will hear it, so I want to check the system volume.

How can I find out what the cur

相关标签:
8条回答
  • 2020-11-27 05:18

    Swift 2.2, make sure to import 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
    
    0 讨论(0)
  • 2020-11-27 05:23

    Try this:

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

    You need to import the MediaPlayer framework.

    0 讨论(0)
  • 2020-11-27 05:27

    You can use the default system's volume View and add to wherever you need it. In my case I required it in my own music player. It's easy and hassle free. Just add the view, and everything is done. This is explained in Apple's MPVolume Class Reference.

    mpVolumeViewParentView.backgroundColor = [UIColor clearColor];
    MPVolumeView *myVolumeView =
    [[MPVolumeView alloc] initWithFrame: mpVolumeViewParentView.bounds];
    [mpVolumeViewParentView addSubview: myVolumeView];
    [myVolumeView release];
    
    0 讨论(0)
  • 2020-11-27 05:27

    I have prepared a class with static methods in order to deal with the volume of ios devices. Let me share with you :)

    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
    }
    }
    
    0 讨论(0)
  • 2020-11-27 05:33

    This works fine:

    Float32 volume;
    UInt32 dataSize = sizeof(Float32);
    
    AudioSessionGetProperty (
                         kAudioSessionProperty_CurrentHardwareOutputVolume,
                         &dataSize,
                         &volume
                         );
    
    0 讨论(0)
  • 2020-11-27 05:38

    Update for Swift

        let vol = AVAudioSession.sharedInstance().outputVolume
    

    The audio session can provide output volume (iOS >= 6.0).

    float vol = [[AVAudioSession sharedInstance] outputVolume];
    NSLog(@"output volume: %1.2f dB", 20.f*log10f(vol+FLT_MIN));
    
    0 讨论(0)
提交回复
热议问题