背景音乐重叠的viewController
问题描述:
当回制作者我有一个游戏,其包括3个视图控制器:背景音乐重叠的viewController
- 的viewController
- settingViewController
- GameViewController
我已经设置的背景音乐和在viewController类中播放它
var backgroundMusic : AVAudioPlayer!
func setUpSounds(){
//button sound
if let buttonSoundPath = NSBundle.mainBundle().pathForResource("buttonClick", ofType: "mp3") {
let buttonSoundURL = NSURL(fileURLWithPath: buttonSoundPath)
do {
try buttonSound = AVAudioPlayer(contentsOfURL: buttonSoundURL)
}catch {
print("could not setup button sound")
}
buttonSound.volume = 0.5
}
//background sound
if let backgroundMusicPath = NSBundle.mainBundle().pathForResource("BackgroundMusic", ofType: "mp3") {
let backgroundMusicURL = NSURL(fileURLWithPath: backgroundMusicPath)
do {
try backgroundMusic = AVAudioPlayer(contentsOfURL: backgroundMusicURL)
}catch {
print("could not setup background music")
}
backgroundMusic.volume = 0.2
/*
set any negative integer value to loop the sound
indefinitely until you call the stop method
*/
backgroundMusic.numberOfLoops = -1
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.setUpSounds()
self.playBackgroundSound()
// Do any additional setup after loading the view, typically from a nib.
}
当我移动到settingViewController然后再回到viewController的声音重放和重叠旧的播放音乐。
这个问题的解决方案是什么?
答
您必须先检查AVAudioPlayer
是否正在播放音乐,然后致电playBackgroundSound
。
您还可以将SoundManager作为单件使用,以便从应用程序的其他部分操纵它。
class SoundManager{
static var backgroundMusicSharedInstance = AVAudioPlayer?
}
在查看
func setUpSounds(){
//background sound
if SoundManager.backgroundMusicSharedInstance == nil {
if let backgroundMusicPath = NSBundle.mainBundle().pathForResource("BackgroundMusic", ofType: "mp3") {
let backgroundMusicURL = NSURL(fileURLWithPath: backgroundMusicPath)
do {
try SoundManager.backgroundMusicSharedInstance = AVAudioPlayer(contentsOfURL: backgroundMusicURL)
}catch {
print("could not setup background music")
}
SoundManager.backgroundMusicSharedInstance!.volume = 0.2
/*
set any negative integer value to loop the sound
indefinitely until you call the stop method
*/
SoundManager.backgroundMusicSharedInstance!.numberOfLoops = -1
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.setUpSounds()
if SoundManager.backgroundMusicSharedInstance!.playing == false{
self.playBackgroundSound()
}
}
没有帮助,还是同样的问题。 –
您使用的是模态或推塞格? – UlyssesR
我已经使用故事板连接了它 –