【问题标题】:Playing sound effect in Xcode在 Xcode 中播放音效
【发布时间】:2020-08-05 17:35:56
【问题描述】:

我在 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()
}

}

【问题讨论】:

  • 你想在播放的时候暂停音效,暂停的时候再播放一遍吗?
  • 我希望它在再次按下按钮时继续播放,也就是说声音相互重叠。

标签: ios swift xcode


【解决方案1】:

您可以在Play 方法中初始化audioPlayer 而不是viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func Play(_ sender: Any) {
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "1", ofType: "mp3")!))
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    } catch {
        print(error)
    }
}

【讨论】:

  • 感谢您的快速回答。如果我复制代码并粘贴它,它会说“只有实例方法可以声明@IBAction”。
  • 你把这个粘贴到哪里了?您必须用我上面提供的方法替换代码中的方法。
  • 我已将部分代码替换为您的代码(与您发布的顺序相同)。请原谅,我是编码新手。
  • 只有在顶层ViewController 之外发布上述代码时,您才会收到此错误。如果你这样做了,把它放在ViewController中。
【解决方案2】:

如果我理解正确,您想在播放声音时阻止再次播放,而在播放完毕后只播放声音 您可以根据声音是否播放来设定条件 (在您的按钮操作中尝试):

 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多