【问题标题】:What is the simplest possible way to add background music to your Swift iOS app?将背景音乐添加到 Swift iOS 应用程序的最简单方法是什么?
【发布时间】:2017-11-26 07:20:09
【问题描述】:

我已经为 ARKit、SceneKit 游戏添加了位置音频和交互式音频,但现在我只想添加在应用程序运行和打开时播放的背景音频,并在应用程序关闭或在后台时停止播放。我可以使用 SceneKit 声音或媒体播放器,但似乎必须有更轻更简单的方法?然而,我只是找到了这些更复杂的选项,我不想在这个应用程序的任何功能上使用过度的东西。有谁知道是否有一个非常简单的机制来播放背景音乐?

【问题讨论】:

    标签: ios audio


    【解决方案1】:

    AVPlayer 非常简单。这是我从 URL 或文件名初始化并循环音频的扩展:

    extension AVPlayer {
        convenience init?(url: URL) {
            let playerItem = AVPlayerItem(url: url)
            self.init(playerItem: playerItem)
        }
        convenience init?(name: String, extension ext: String) {
            guard let url = Bundle.main.url(forResource: name, withExtension: ext) else {
                return nil
            }
            self.init(url: url)
        }
        func playFromStart() {
            seek(to: CMTimeMake(0, 1))
            play()
        }
        func playLoop() {
            playFromStart() 
            NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.currentItem, queue: nil) { notification in
                if self.timeControlStatus == .playing {
                    self.playFromStart()
                }
            }
        }
        func endLoop() {
            pause()
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 2012-04-30
      • 1970-01-01
      相关资源
      最近更新 更多