快速地在一个按钮上播放两个声音

时间:2017-01-25 13:43:02

标签: xcode audio swift3

我有三个按钮,每个按钮应该播放不同的声音。我的问题是,一旦点击第二个按钮也会播放第一个声音。 有什么我可以做的来解决这个问题吗?

 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()

    }

    }

2 个答案:

答案 0 :(得分:0)

检查故事板并确保您没有将第二个按钮连接到第一个和第二个@IBAction

这样做可以右键单击故事板中的第二个按钮。在Touch up Inside - 事件中,应该只有一个连接beep。在显示catSound的位置,单击小x将其删除。

答案 1 :(得分:0)

您可以尝试停止其他AudioPlayers吗?

 @IBAction func beep(_ sender: UIButton) {
    audioPlayer.stop()
    audioPlayer2.stop()
    audioPlayer1.play()

    }