目前我有一个使用AVFoundation播放背景音乐的主屏幕。如果你点击播放,音乐会停止(这就是我想要的)。
如果您移动到说明屏幕,音乐会继续(我想要),但是当您单击返回主屏幕时,背景音乐会继续(我想要),但是新曲目会从顶部开始。
在我看来,我理想需要的是一个if语句,当我返回主屏幕时(如果它已经在播放),它会阻止音乐重新启动。我已经浏览了互联网,但我找不到任何可行的建议。
这就是我目前正在使用的内容,
class firstPageViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
backgroundMusic = self.setupAudioPlayerWithFile("background", type:"mp3")
backgroundMusic.volume = 0.3
backgroundMusic.numberOfLoops = -1
backgroundMusic.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
var backgroundMusic = AVAudioPlayer()
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
//1
var path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
var url = NSURL.fileURLWithPath(path!)
//2
var error: NSError?
//3
var audioPlayer:AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
//4
return audioPlayer!
}
@IBAction func startGame(sender: UIButton) {
backgroundMusic.stop()
}
@IBAction func instructionsButton(sender: UIButton) {
}
答案 0 :(得分:1)
var isMusicPlaying = 0
class firstPageViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
backgroundMusic = self.setupAudioPlayerWithFile("background", type:"mp3")
if isMusicPlaying == 0 {
backgroundMusic.volume = 0.3
backgroundMusic.numberOfLoops = -1
backgroundMusic.play()
}
if backgroundMusic.playing == true {
isMusicPlaying = 1
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
var backgroundMusic = AVAudioPlayer()
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
//1
var path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
var url = NSURL.fileURLWithPath(path!)
//2
var error: NSError?
//3
var audioPlayer:AVAudioPlayer?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
//4
return audioPlayer!
}