gpt4 book ai didi

ios - 如何多次使用 audioPlayerDidFinishPlaying

转载 作者:行者123 更新时间:2023-11-28 06:25:01 24 4
gpt4 key购买 nike

我在 MainStoryBoard 上创建了带有图像的 UIButton。当我按下该按钮时,它会播放一个音频文件,并且在播放音频时 UIButton 的背景颜色会发生变化。

audioPlayerDidFinishPlaying1 被正确调用,但是 audioPlayerDidFinishPlaying2似乎没有被调用。我很感激任何帮助我解决这个问题的建议。

    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!

func Player(url: URL) {
do {
try player = AVAudioPlayer(contentsOf:url)
player.play()
yourButton.isSelected = true
player.delegate = self
} catch {
print(error)
}
}

func Player1(url: URL) {
do {
try player = AVAudioPlayer(contentsOf:url)
player.play()
yourButton2.isSelected = true
player.delegate = self
} catch {
print(error)
}
}
@IBAction func pushButton1(sender: UIButton) {
Player(url: url1)
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
yourButton.isSelected = false

}

@IBAction func pushButton2(sender: UIButton) {
Player1(url: url2)
}
func audioPlayerDidFinishPlaying2(_ player: AVAudioPlayer, successfully flag: Bool) {
yourButton2.isSelected = false
}

最佳答案

您正在使用 Player1/Player 方法在本地创建播放器。所以当方法结束时,播放器将被释放。将生成的播放器保留为类成员,这样它就不会在方法退出时被释放

在你的类中添加:

class YourClass
{
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!

fileprivate var player1: AVAudioPlayer?
fileprivate var player2: AVAudioPlayer?

.
.
.

func Player(url: URL) {
do {
try player1 = AVAudioPlayer(contentsOf:url)
player1!.play()
yourButton.isSelected = true
player1!.delegate = self
} catch {
print(error)
}
}

另一件事.. 您正在使用委托(delegate)方法 audioPlayerDidFinishPlaying,它是 AVAudioPlayer 的委托(delegate)方法。但是 audioPlayerDidFinishPlaying2 不是,所以在这里没用。由于您有两名玩家,一个类(class)作为代表,您需要确定哪个玩家已完成并更改正确的按钮。

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if (player === player1) {
yourButton.isSelected = false
} else if (player === player2) {
yourButton2.isSelected = false
}
}

关于ios - 如何多次使用 audioPlayerDidFinishPlaying,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42185549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com