【问题标题】:Play audio file in sequence in Swift, where the second sound gets played on repeat在 Swift 中按顺序播放音频文件,其中第二个声音重复播放
【发布时间】:2018-12-28 19:06:41
【问题描述】:

对于我游戏中的背景音乐,我想播放两个声音。第一个声音在开始时只播放一次(4 小节介绍)。之后,第二个声音(主音乐)无限循环播放。不幸的是,下面的代码同时播放声音,而不是按顺序播放(当我查看 AVQueuePlayer 时,我无法弄清楚如何只循环两个声音中的第二个):

var backgroundMusicPlayer: AVAudioPlayer!
var backgroundMusicPlayerIntro: AVAudioPlayer!

func playBackgroundMusic(filename: String, withIntro intro: String) {
    let resourceUrl = Bundle.main.url(forResource: filename, withExtension: nil)
    let resourceUrlIntro = Bundle.main.url(forResource: intro, withExtension: nil)

    guard let url = resourceUrl, let urlIntro = resourceUrlIntro else {
        print("Could not find files: \(intro) and/or \(filename)")
        return
    }

    //play the intro first before playing the main loop
    do {
        try backgroundMusicPlayerIntro = AVAudioPlayer(contentsOf: urlIntro)
        backgroundMusicPlayerIntro.numberOfLoops = 1
        backgroundMusicPlayerIntro.prepareToPlay()
        backgroundMusicPlayerIntro.play()
    } catch {
        print("Could not create audio player!")
        return
    }

    //main music that gets played on repeat
    do {
        try backgroundMusicPlayer = AVAudioPlayer(contentsOf: url)
        backgroundMusicPlayer.numberOfLoops = -1
        backgroundMusicPlayer.prepareToPlay()
        backgroundMusicPlayer.play()
    } catch {
        print("Could not create audio player!")
        return
    }
}

【问题讨论】:

  • "当我查看 AVQueuePlayer 时,我无法弄清楚如何只循环两个声音中的第二个" 不过,这是一个很好的方法。

标签: ios swift audio


【解决方案1】:

您同时启动 2 个玩家。您可以使用一个播放器属性,当在第一个声音结束时调用audioPlayerDidFinishPlaying 方法时,AVAudioPlayerDelegate 可以播放第二个声音。基本上是这样的:

class Player: AVAudioPlayerDelegate {

    var audioPlayer: AVAudioPlayer?

    func startPlayingFirstSong() {
        // your 1st do/catch code...
        try audioPlayer = AVAudioPlayer(contentsOf: urlIntro)
        audioPlayer?.delegate = self
    }

    // AVAudioPlayer will call this func when the first song ends:
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        // your 2nd do/catch code...
        try audioPlayer = AVAudioPlayer(contentsOf: url)
        audioPlayer?.delegate = self
    }

}

let player = Player()
player.startPlayingFirstSong()

【讨论】:

  • 我将如何实现 audioPlayerDidFinishPlaying 方法(在此方法中,我是否包含播放第二个声音的代码?)然后,我将如何在 intro 播放完毕后调用 audioPlayerDidFinishPlaying?
猜你喜欢
  • 2017-12-21
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
相关资源
最近更新 更多