使用 Swift 2.1 在 iOS 中播放两种声音

Playing Two Sounds in iOS Using Swift 2.1

我有一个包含选择器轮和播放按钮的应用程序。当用户选择所需的声音并单击播放按钮时,声音就会播放。除此之外,我还有一个 "Random" 按钮,它会生成一个随机数,将选择器轮移动到适当的数组索引,然后播放声音。所有这些都可以正常工作。

问题是我正在尝试添加一个 "Combo" 按钮,它基本上与 "Random" 按钮执行相同的操作,但不是只播放 1 种声音,我希望它播放 2 种或3.

这是我现有的代码(playComboSound 函数有问题):

// Play Audio
var audioPlayer = AVAudioPlayer()

func playAudio() {
    do {
        if let bundle = NSBundle.mainBundle().pathForResource(Sounds[selection], ofType: "mp3") {
            let alertSound = NSURL(fileURLWithPath: bundle)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        }
    } catch {
        print(error)
    }
}

@IBAction func playRandomSound(sender: AnyObject) {

    // Generate Random Number Based on SoundNames Array Count and assign to Selection
    let randomNumber = Int(arc4random_uniform(UInt32(SoundNames.count)))
    selection = randomNumber

    // Move Picker Wheel to Match Random Number and Play Sound
    self.picker.selectRow(selection, inComponent: 0, animated: true)
    playAudio()
}

@IBAction func playComboSound(sender: AnyObject) {
    // Generate Random Number Based on SoundNames Array Count and assign to Selection
    let randomNumber1 = Int(arc4random_uniform(UInt32(SoundNames.count)))
    selection = randomNumber1

    // Move Picker Wheel to Match Random Number and Play Sound
    self.picker.selectRow(selection, inComponent: 0, animated: true)
    playAudio()

    // Generate Random Number Based on SoundNames Array Count and assign to Selection
    let randomNumber2 = Int(arc4random_uniform(UInt32(SoundNames.count)))
    selection = randomNumber2

    // Move Picker Wheel to Match Random Number and Play Sound
    self.picker.selectRow(selection, inComponent: 0, animated: true)
    playAudio()
}

当我点击 playComboSound 按钮时,它基本上与 playRandomSound 按钮一样。移动选择器轮并播放声音,但它只播放一次而不是两次。如果我在两者之间睡一觉,我会在播放两种声音方面取得一定程度的成功,但它似乎只移动一次选择器轮(对于第二种声音)。任何帮助将不胜感激!谢谢

Moves the picker wheel and plays the sound, but it only does it once instead of twice.

它播放一次声音,因为对 playAudio 的第二次调用用一个新的 AVAudioPlayer 实例覆盖了共享的 audioPlayer 变量,该实例释放了第一个实例。您应该保留对所有活动音频播放器的 array/set 引用,以防止它们被释放,并且只有在它们完成后才将它们从该集合中删除(使用 AVAudioPlayerDelegate 回调来检测播放器何时已完成)。

If I put a sleep in between I get some level of success in playing two sounds, but it only ever seems to move the picker wheel once (for the second sound).

睡眠有帮助,因为当主线程处于睡眠状态时,AVFoundation 的线程有机会 运行 并且它们可以在第二次调用 [=10= 之前开始播放第一个 AVAudioPlayer ] 覆盖它并且它被释放。不过,您在这里依赖于未定义的行为。

it only ever seems to move the picker wheel once (for the second sound)

这是预期的行为。在选择器轮上只能选择一个项目。对 selectRow 的第二次调用会覆盖第一个。