切换按钮静音(快速)

时间:2015-04-16 03:10:36

标签: ios swift audio avfoundation

我要做的是在我的应用程序中有一个设置页面,当点击一个开关(其原始状态为关闭)时,它将使整个应用程序静音。到目前为止,我的代码可以做的只是静音当前视图并且它工作得很好,直到我转到我的主视图然后音乐仍在播放与此相关联,当我转回设置页面时,静音开关返回到原来的关闭状态,音乐再次播放。我想知道如何修复我的代码,以便在打开时它可以消除所有噪音。这是我的代码,感谢您阅读和帮助:

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

}

1 个答案:

答案 0 :(得分:3)

你可以这样做:

<强> 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