首页 > 解决方案 > 背景音乐,我的音乐相互重叠,我想让音乐循环播放

问题描述

导入 UIKit 导入 AVFoundation

类 BackgroundViewController: UIViewController { var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = .white

    playBackgroundStartMusic()
}

override func viewWillAppear(_ animated: Bool) {
    audioPlayer.stop()
}

//MARK: - Background Music

func playBackgroundStartMusic() {
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "IntroMusic", ofType: "wav")!))
        audioPlayer.prepareToPlay()
        audioPlayer.play()
        audioPlayer.numberOfLoops = -1
    }
    catch {
        print(error)
    }
}

}

标签: swift

解决方案


如果您遇到音乐覆盖视图更改的问题,只需将 AVFoundation 中的 audioPlayer.stop() 放在显示下一个屏幕的按钮上,这样背景音乐就会停止并且不再播放。


推荐阅读