快速检测音量变化

我在检测有人何时按下音量调高按钮时遇到问题。目前,我只是播放文件,但我想知道用户何时按下按钮以在音量变化时显示警报。我正在开发Swift,并且正在使用AVFoundation创建此播放器。目前,我找不到适用于Swift的东西。我是这种语言的新手。

import UIKit

import AVFoundation

class ViewController: UIViewController {

var backgroundMusicPlayer = AVAudioPlayer()

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.

playBackgroundMusic("IronBacon.mp3")

}

func playBackgroundMusic(filename:String){

let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)

print(url)

guard let newUrl = url else{

print("couldn't find file: \(filename)")

return

}

do{

backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newUrl)

backgroundMusicPlayer.numberOfLoops = -1

backgroundMusicPlayer.prepareToPlay()

}catch let error as NSError{

print(error.description)

}

}

@IBAction func playPauseAction(sender: UIButton) {

sender.selected = !sender.selected

if sender.selected {

backgroundMusicPlayer.play()

} else {

backgroundMusicPlayer.pause()

}

}

func ShowAlert(title: String, message: String, dismiss: String) {

let alertController = UIAlertController(title: title, message:

message, preferredStyle: UIAlertControllerStyle.Alert)

alertController.addAction(UIAlertAction(title: dismiss, style: UIAlertActionStyle.Default,handler: nil))

self.presentViewController(alertController, animated: true, completion: nil)

}

func volumeUp(){

ShowAlert( "example", message: "example", dismiss: "close")

}

func volumeDown(){

ShowAlert( "example", message: "example", dismiss: "close")

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}

回答:

这应该可以解决问题。

class ViewController: UIViewController {

// MARK: Properties

let notificationCenter = NSNotificationCenter.defaultCenter()

// MARK: Lifecycle

override func viewDidAppear(animated: Bool) {

super.viewDidAppear(animated)

notificationCenter.addObserver(self,

selector: #selector(systemVolumeDidChange),

name: "AVSystemController_SystemVolumeDidChangeNotification",

object: nil

)

}

override func viewDidDisappear(animated: Bool) {

super.viewDidDisappear(animated)

notificationCenter.removeObserver(self)

}

// MARK: AVSystemPlayer - Notifications

func systemVolumeDidChange(notification: NSNotification) {

print(notification.userInfo?["AVSystemController_AudioVolumeNotificationParameter"] as? Float)

}

}

以上是 快速检测音量变化 的全部内容, 来源链接: utcz.com/qa/400865.html

回到顶部