Ios 返回creator viewController时背景音乐重叠
我有一个由3个视图控制器组成的游戏:Ios 返回creator viewController时背景音乐重叠,ios,swift,uiviewcontroller,avfoundation,Ios,Swift,Uiviewcontroller,Avfoundation,我有一个由3个视图控制器组成的游戏: 视图控制器 设置视图控制器 游戏视图控制器 我已经设置了背景音乐并在viewController类中播放 var backgroundMusic : AVAudioPlayer! func setUpSounds(){ //button sound if let buttonSoundPath = NSBundle.mainBundle().pathForResource("buttonClick", ofType: "m
- 视图控制器
- 设置视图控制器
- 游戏视图控制器
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()
}
}
没有帮助,还是同样的问题。你是使用模态还是推式segue?我已经用故事板连接好了,但是你如何设置segue?在连接中单击时,右侧显示的名称是什么?看看这个链接显示(例如推送),这也是我的案例中显示的内容