如何同时停止2种不同的播放音频?播放音乐时,另一个按钮同时播放音频。抱歉我的英文。
NoiseMaker
:
import AVFoundation
class NoiseMaker {
let audioFileNames = ["guitar", "applause", "monster", "bubbles"]
let players: [AVAudioPlayer?]
init() {
players = audioFileNames.map { filename in
if let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "wav") {
return try? AVAudioPlayer(contentsOfURL: url)
} else {
return nil
}
}
}
func play(index: Int) {
if !players.isEmpty && index >= 0 && index < players.count {
players[index]?.play()
}
}
}
ViewController
:
import UIKit
class ViewController: UIViewController {
let noiseMaker = NoiseMaker()
@IBAction func playSound(sender: UIButton) {
noiseMaker.play(sender.tag)
}
}
答案 0 :(得分:0)
为当前播放的声音添加实例变量。当您点击按钮时,向当前播放的声音发送停止消息,将新声音复制到实例变量,然后开始播放该声音。