我在视图加载时运行AVAudioPlayer
的实例。从另一个ViewController
我有UISwitch
来停止音乐。我可以从交换机收到Bool
并看到它在console
中调用正确的功能,但我无法让音乐停止播放。我试图停止,暂停和改变音量,但无济于事。当应用程序关闭(双击主页并向上滑动)并且开关状态保持关闭时,音乐将无法播放。如果您打开开关,音乐将播放但不会停止。
代码:
var player:AVAudioPlayer = AVAudioPlayer()
let optionDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
do{
let audioPath = Bundle.main.path(forResource: "backgroundmusic", ofType: "wav")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
player.volume = 0.2
if optionDefaults.value(forKey: "musicOn") != nil {
let musicOn: Bool = optionDefaults.value(forKey: "musicOn") as! Bool
if musicOn == false {
print("********** Music is off **********")
player.stop()
}
else {
print("********** Music is On **********")
player.play()
}
}
} catch {
print("AVPlayer did not initialize")
}
player.numberOfLoops = -1
}
*******代码切换********
let optionDefaults = UserDefaults.standard
@IBOutlet weak var musicOnOff: UISwitch!
var musicOn : Bool = true
@IBAction func switchToGame(sender: UIButton) {
if musicOnOff.isOn{
musicOn = true
optionDefaults.set(musicOn, forKey: "musicOn")
}
if musicOnOff.isOn == false{
musicOn = false
optionDefaults.set(musicOn, forKey: "musicOn")
}}
override func viewDidLoad() {
super.viewDidLoad()
if optionDefaults.value(forKey: "musicOn") != nil {
let musicOn: Bool = optionDefaults.value(forKey: "musicOn") as! Bool
if musicOn == false {
musicOnOff.isOn = false
}
else{
musicOnOff.isOn = true
}
}}
答案 0 :(得分:0)
仅在视图加载完成时才播放音乐。如果您想在切换切换时停止并播放,只需在切换开关动作上调用palyOrStopMusic方法
var player:AVAudioPlayer = AVAudioPlayer()
let optionDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
playOrStopMusic()
}
func playOrStopMusic(){
do{
let audioPath = Bundle.main.path(forResource: "backgroundmusic", ofType: "wav")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
player.volume = 0.2
if optionDefaults.value(forKey: "musicOn") != nil {
let musicOn: Bool = optionDefaults.value(forKey: "musicOn") as! Bool
if musicOn == false {
print("********** Music is off **********")
player.stop()
}
else {
print("********** Music is On **********")
player.play()
}
}
} catch {
print("AVPlayer did not initialize")
}
player.numberOfLoops = -1
}
*******代码切换********
let optionDefaults = UserDefaults.standard
@IBOutlet weak var musicOnOff: UISwitch!
var musicOn : Bool = true
@IBAction func switchToGame(sender: UIButton) {
if musicOnOff.isOn{
musicOn = true
optionDefaults.set(musicOn, forKey: "musicOn")
}else{
musicOn = false
optionDefaults.set(musicOn, forKey: "musicOn")
}
playOrStopMusic()
}
override func viewDidLoad() {
super.viewDidLoad()
playOrStopMusic()
}