当我 return 到原来的 VC 时,音乐播放歌曲

Music playing over the song when i return to the original VC

我正在为我的应用程序使用 xcode 9 和 swift 4。在我的应用程序中,我在 viewDidLoad 中播放音乐。当我退出视图控制器转到另一个视图时,它会继续正常播放。然而,当我 return 到那个视图控制器时,歌曲又开始播放了。这首歌与第一次加载的歌曲重叠。你们有什么想法可以阻止这种情况发生吗?

do
{
    let audioPath = Bundle.main.path(forResource: "APP4", ofType: "mp3")
    try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
}
catch
{
    //catch error
}

let session = AVAudioSession.sharedInstance()

do
{
    try session.setCategory(AVAudioSessionCategoryPlayback)
}
catch
{
}

player.numberOfLoops = -1
player.play()

它又开始播放了,因为你的viewDidLoad又被调用了,要求它再次播放。最简单的解决方法是保留一个静态 bool 变量,以便在您已经进行此调用时进行跟踪。

static var isMusicPlaying: Bool = false

在您的 viewDidLoad 中,您可以将代码放在调用播放的代码之前。

guard !isMusicPlaying else {
   return
}
isMusicPlaying = true