获取系统音量 iOS

发布于 2024-12-02 00:56:48 字数 71 浏览 1 评论 0原文

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

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

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 current system volume is?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

羁客 2024-12-09 00:56:48

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));

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));
蘑菇王子 2024-12-09 00:56:48

Swift 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) - 重要

Swift 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) - important

两人的回忆 2024-12-09 00:56:48

试试这个:

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

您需要导入 MediaPlayer 框架。

Try this:

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

You need to import the MediaPlayer framework.

各空 2024-12-09 00:56:48

这工作正常:

Float32 volume;
UInt32 dataSize = sizeof(Float32);

AudioSessionGetProperty (
                     kAudioSessionProperty_CurrentHardwareOutputVolume,
                     &dataSize,
                     &volume
                     );

This works fine:

Float32 volume;
UInt32 dataSize = sizeof(Float32);

AudioSessionGetProperty (
                     kAudioSessionProperty_CurrentHardwareOutputVolume,
                     &dataSize,
                     &volume
                     );
别挽留 2024-12-09 00:56:48

对于Swift 2

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

For Swift 2:

let volume = AVAudioSession.sharedInstance().outputVolume   
print("Output volume: \(volume)")
高速公鹿 2024-12-09 00:56:48

您可以使用默认系统的卷视图并添加到您需要的任何地方。就我而言,我需要在我自己的音乐播放器中使用它。这既简单又无麻烦。只需添加视图,一切就完成了。 Apple 的 MPVolume 类参考。

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

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];
爱人如己 2024-12-09 00:56:48

为了处理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
}
}

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
}
}
单身情人 2024-12-09 00:56:48

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文