2017-06-07 110 views
-1

這是我的一個Xcode項目的代碼。當我按下「播放()」時,會發生短鼓聲。事情是,當我連續多次敲擊自定義視圖時,我希望快速鼓聲連續發生。然而,聲音在完成剪輯(2秒)完成後發生,留下很多死區。我嘗試了很多不同的事情,但我做不到。如何快速按下按鈕在Xcode上生成聲音?

@IBOutlet weak var tabla: TablaHead! 

var tablaSoundUrl = NSURL(fileURLWithPath: Bundle.main.path(forResource: "TablaSound", ofType: "mp3")!) 
var tablaAudioPlayer = AVAudioPlayer() 


override func viewDidLoad() { 
    super.viewDidLoad() 
    tablaAudioPlayer = try! AVAudioPlayer(contentsOf: tablaSoundUrl as URL) 
} 

@IBAction func tapped(_ sender: UITapGestureRecognizer) { 
    if sender.state == .ended { 
     playNoise() 
    } 
} 

public func playNoise() { 
    if (tablaAudioPlayer.isPlaying) { 
     tablaAudioPlayer.stop() 
     tablaAudioPlayer.play() 
    } else { 
     tablaAudioPlayer.play() 
    } 
} 

回答

0

嘗試是這樣的

@IBOutlet weak var tabla: TablaHead! 

var tablaSoundUrl = NSURL(fileURLWithPath: Bundle.main.path(forResource: "TablaSound", ofType: "mp3")!) 
var tablaAudioPlayer = AVAudioPlayer() 
var tapsCount = 0 

override func viewDidLoad() { 
    super.viewDidLoad() 
    tablaAudioPlayer = try! AVAudioPlayer(contentsOf: tablaSoundUrl as URL) 
} 

@IBAction func tapped(_ sender: UITapGestureRecognizer) { 
    tapsCount += 1 
    if sender.state == .ended && tapsCount == 1 { 
     playNoise() 
    } 
} 

public func playNoise() { 
    tapsCount -= 1 
    tablaAudioPlayer.play() 
    if tapsCount > 0 { 
     playNoise() 
    } 
} 
+0

沒有運氣。我認爲問題是我完全不瞭解AVAudioPlayer。謝謝你嘗試! –