i have three buttons and each are supposed to play a different sound which they do. My problem is that the second button once clicked also plays the first sound. is there something i could do to fix this?
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
var audioPlayer1 = AVAudioPlayer()
var audioPlayer2 = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "OhNo", ofType: "mp3")! ))
audioPlayer.prepareToPlay()
}
catch{
print(error)
}
do {
audioPlayer1 = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "beep2", ofType: "mp3")! ))
audioPlayer1.prepareToPlay()
}
catch{
print(error)
}
do {
audioPlayer2 = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "beep10", ofType: "mp3")! ))
audioPlayer2.prepareToPlay()
}
catch{
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func catSound(_ sender: UIButton) {
audioPlayer.play()
}
@IBAction func beep(_ sender: UIButton) {
audioPlayer1.play()
}
@IBAction func beep10(_ sender: UIButton) {
audioPlayer2.play()
}
}
Check your storyboard and make sure you haven't connected the second button to both the first and second @IBAction
.
Do this buy right-clicking on the second button in the storyboard. On the Touch up Inside
-event there should be only one connection, the beep
. On the one where it says catSound
, click the little x to remove it.
Can you try stopping the other AudioPlayers?
@IBAction func beep(_ sender: UIButton) {
audioPlayer.stop()
audioPlayer2.stop()
audioPlayer1.play()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.