切换按钮静音(快速)
Posted
技术标签:
【中文标题】切换按钮静音(快速)【英文标题】:Switch button to mute (swift) 【发布时间】:2015-04-16 03:10:36 【问题描述】:我想要做的是在我的应用程序中有一个设置页面,当点击一个开关(其原始状态为关闭)时,它将使整个应用程序静音。到目前为止,我的代码可以做的是仅使当前视图静音,并且效果很好,直到我转到我的主视图然后仍在播放与该视图相关联的音乐,并且当我转到设置页面时,静音开关被返回恢复到原来的关闭状态,音乐再次播放。我想知道如何修复我的代码,以便在打开它时静音所有噪音。这是我的代码,感谢您的阅读和帮助:
import UIKit
import AVFoundation
var songs = ""
var backgroundMusicPlayer: AVAudioPlayer!
func playBackgroundMusic(filename: String)
let url = NSBundle.mainBundle().URLForResource(
filename, withExtension: nil)
if (url == nil)
println("Could not find file: \(filename)")
return
var error: NSError? = nil
backgroundMusicPlayer =
AVAudioPlayer(contentsOfURL: url, error: &error)
if backgroundMusicPlayer == nil
println("Could not create audio player: \(error!)")
return
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
class settingsView: UIViewController
@IBOutlet weak var mySwitch: UISwitch!
@IBAction func switchPressed(sender: AnyObject)
playBackgroundMusic(songs)
if mySwitch.on
backgroundMusicPlayer.pause()
else
backgroundMusicPlayer.play()
override func viewDidLoad()
super.viewDidLoad()
// Do view setup here.
songs = "settingsBackground.mp3"
switchPressed(self)
【问题讨论】:
将此开关值存储在 NSUSerdefault 中,并使用每个视图控制器的 viewDidload 或 viewwillappear 的值。如果它比增加音量等等... 【参考方案1】:你可以这样做:
MainViewController.swift
import UIKit
class ViewController: UIViewController
override func viewDidLoad()
super.viewDidLoad()
// Do view setup here.
let status = NSUserDefaults().stringForKey("playerStatus")
if status == "Off"
if (backgroundMusicPlayer?.playing != nil)
backgroundMusicPlayer?.stop()
else
songs = "1.mp3"
playBackgroundMusic(songs)
settingsView.swift
import UIKit
class settingsView: UIViewController
@IBOutlet weak var mySwitch: UISwitch!
@IBAction func switchPressed(sender: AnyObject)
if mySwitch.on
NSUserDefaults().setObject("on", forKey: "playerStatus")
playBackgroundMusic(songs)
else
NSUserDefaults().setObject("Off", forKey: "playerStatus")
backgroundMusicPlayer!.stop()
override func viewDidLoad()
super.viewDidLoad()
let status = NSUserDefaults().stringForKey("playerStatus")
if status == "Off"
mySwitch.setOn(false, animated: false)
这里是完整的工作项目:https://github.com/DharmeshKheni/Switch-with-AudioPlayer
【讨论】:
以上是关于切换按钮静音(快速)的主要内容,如果未能解决你的问题,请参考以下文章