我在主控板上创建了三个uibutton。
当我按“yourButton3”时,player3不被调用。
我发现修改else if子句或给player3赋值可以解决这个问题,但不知道如何解决。
override func viewDidLoad() {
super.viewDidLoad()
player1?.delegate = self
player2?.delegate = self
player3?.delegate = self
}
let url1 = Bundle.main.bundleURL.appendingPathComponent("music1.mp3")
let url2 = Bundle.main.bundleURL.appendingPathComponent("music2.mp3")
@IBOutlet weak var yourButton: customButton!
@IBOutlet weak var yourButton2: customButton!
@IBOutlet weak var yourButton3: customButton!
fileprivate var player1:AVAudioPlayer?
fileprivate var player2:AVAudioPlayer?
fileprivate var player3:AVAudioPlayer?
@IBAction func pushButton1(sender: UIButton) {
Player(url: url1)
}
@IBAction func pushButton2(sender: UIButton) {
Player1(url: url2)
}
@IBAction func pushButton3(_ sender: UIButton) {
Player(url: url2)
player1!.play()
}
//player3 is not called in this code
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if (player === player1) {
yourButton.isSelected = false
} else if (player === player2) {
yourButton2.isSelected = false
} else if (player === player3) {
yourButton.isSelected = false
player2!.play()
yourButton2.isSelected = false
}
}
func Player(url: URL) {
do {
try player1 = AVAudioPlayer(contentsOf:url)
player1!.play()
yourButton.isSelected = true
player1!.delegate = self
} catch {
print(error)
}
}
func Player1(url: URL) {
do {
try player2 = AVAudioPlayer(contentsOf:url)
player2!.play()
yourButton2.isSelected = true
player2!.delegate = self
} catch {
print(error)
}
}
func Player3(url: URL, url2: URL) {
do {
try player1 = AVAudioPlayer(contentsOf:url)
try player2 = AVAudioPlayer(contentsOf: url2)
player1!.play()
yourButton.isSelected = true
player1!.delegate = self
} catch {
print(error)
}
}
最佳答案
您的Player(url:)
函数中没有init player3,因此player === player3
永远不会是真的。
您可以按如下方式编辑Player3(url:, url2:)
函数:
func Player3(url: URL, url2: URL) {
do {
try player3 = AVAudioPlayer(contentsOf:url)
try player2 = AVAudioPlayer(contentsOf: url2)
player3!.play()
yourButton.isSelected = true
player3!.delegate = self
player2!.delegate = self
} catch {
print(error)
}
}
这样称呼:
@IBAction func pushButton3(_ sender: UIButton) {
Player3(url: url1, url2: url2)
}