【发布时间】:2016-02-09 15:42:24
【问题描述】:
我有一个包含选择轮和播放按钮的应用。当用户选择想要的声音并点击播放按钮时,声音就会播放。除此之外,我还有一个“随机”按钮,它将生成一个随机数,将选择轮移动到适当的数组索引,然后播放声音。所有这些工作正常。
问题是我正在尝试添加一个“组合”按钮,该按钮基本上与“随机”按钮的作用相同,但我希望它播放 2 或 3 个声音,而不是只播放 1 个声音。
这是我现有的代码(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 按钮相同。移动选择轮并播放声音,但它只执行一次而不是两次。如果我在两者之间进行睡眠,我会在播放两个声音方面取得一定程度的成功,但它似乎只移动了一次选择轮(对于第二个声音)。任何帮助将不胜感激!谢谢。
【问题讨论】:
-
@TamasZahola 很好的答案!基本上你需要创建第二个音频播放器...
audioPlayer2这样你就可以一次播放两个声音。否则,当你去播放第二个声音时,第一个会停止并被第二个替换。
标签: ios iphone xcode avaudioplayer