ios - 在 Swift 中按顺序播放音频文件,其中第二个声音重复播放

标签 ios swift audio

对于我的游戏中的背景音乐,我想播放两种声音。第一个声音在开始时仅播放一次(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
    }
}

最佳答案

您将同时启动 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()

关于ios - 在 Swift 中按顺序播放音频文件,其中第二个声音重复播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53963219/

相关文章:

iphone - iPhone 的 Objective-C 中的面向方面编程

swift - 按下按钮后以编程方式删除 UILabel

audio - 删除ReCaptcha中的音频?

audio - 通过音量和BPM控制视频输入/可视化

ios - 在 ios 6 项目中,使用 ARC,从函数内部创建的函数 NSDictionary 返回是否安全?

ios - 在 iOS 包中搜索全文的工具

ios - 如何处理 SKShapeNode 子类中的触摸?

使用 UIDocumentInteractionController 时,Swift 崩溃 wen 敲击 “Open in Instagram”

python - 如何在保留 Python 中的采样频率的同时更改 wav 文件的速度

ios - 获取文件上传者的UID