Подтвердить что ты не робот

Получить системный том iOS

Мой случай прост: Мне нужно воспроизвести предупредительный сигнал и вы хотите, чтобы пользователь услышал его, поэтому я хочу проверить системный том.

Как узнать, что представляет собой текущий системный том?

4b9b3361

Ответ 1

Аудиозапись может обеспечивать выходной том (iOS >= 6.0).

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

Ответ 2

Попробуйте следующее:

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

Вам нужно импортировать среду MediaPlayer.

Ответ 3

Это отлично работает:

Float32 volume;
UInt32 dataSize = sizeof(Float32);

AudioSessionGetProperty (
                     kAudioSessionProperty_CurrentHardwareOutputVolume,
                     &dataSize,
                     &volume
                     );

Ответ 4

Для Swift 2:

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

Ответ 5

Вы можете использовать представление системного объема по умолчанию и добавить туда, где вам это нужно. В моем случае я требовал его в своем собственном музыкальном проигрывателе. Это легко и удобно. Просто добавьте представление, и все будет сделано. Это объясняется в Apple Описание класса MPVolume.

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

Ответ 6

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) - важный

Ответ 7

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

Ответ 8

Я подготовил класс со статическими методами, чтобы иметь дело с объемом 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
}
}