首页 > 解决方案 > 在 Xcode 中播放音效

问题描述

我在 Xcode 中创建了一个播放短音效的按钮。我无法在播放时重新触发按钮/声音。因此,我必须等到声音消失才能重复效果。我的意图是每次按下按钮时,声音效果都会开始播放,即使它仍在淡出。有谁知道如何实现这一目标?我正在使用 XCode 11.6。我的代码如下。提前谢谢了。

导入 UIKit 导入 AVFoundation

类视图控制器:UIViewController {

var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "1", ofType: "mp3")!))
        audioPlayer.prepareToPlay()
    } catch {
        print(error)
    }
}

@IBAction func Play(_ sender: Any) {
    audioPlayer.play()
}

}

标签: iosswiftxcode

解决方案


如果我理解正确,您想在播放声音时阻止再次播放,并在播放完毕后播放声音,这样您就可以根据是否播放声音做出条件(在您的按钮操作中尝试):

 if audioPlayer.isPlaying(){
   // your statement when sound is playing in other word nothing to do
 }else{
   // your statement when sound is not playing and you want to start play
      audioPlayer.play()
 }

https://developer.apple.com/documentation/avfoundation/avaudioplayer/1390139-isplaying


推荐阅读