如何为正在播放的声音添加延迟 swift

How to add a delay to a sound being played with swift

我是一个 swift 初学者,正在做一个教程项目(魔法 8 球),并且在以下方面取得了成功: - 按下 "Ask" 按钮时播放特定的声音。 - 为每个随机选择的图像播放特定的声音

但是现在只要按下按钮就应该播放的声音只播放一次,从那以后我只能听到每张图片显示的声音。这是因为我在 "if - else" 循环中 "stuck" 吗?或者我是否必须延迟为阵列中的每个图像播放的声音?

非常感谢您的帮助!

这是我的代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBOutlet weak var magicBall: UIImageView!

    var magicBallDisplay = 1
    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

      magicBall.image = #imageLiteral(resourceName: "theanswerisyes")

    }

    @IBAction func askButtonPressed(_ sender: UIButton) {

        let magicBallArray = [ #imageLiteral(resourceName: "askagainlater"),#imageLiteral(resourceName: "no"),#imageLiteral(resourceName: "theanswerisyes"),#imageLiteral(resourceName: "yes"),#imageLiteral(resourceName: "noidea")]
        magicBall.image = magicBallArray.randomElement()

        let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "Ask", ofType: "wav")!)

        do{
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)

        }catch {
            print("there was some error. The error was \(error)")
        }
        audioPlayer.play()

        if (magicBall.image?.isEqual(UIImage(named: "yes")))! {

            let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "yes", ofType: "mp3")!)
            do{
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)

            } catch {
            print("there was some error. The error was \(error)")
            }
             audioPlayer.play()
        }
        else if (magicBall.image?.isEqual(UIImage(named: "no")))! {
            let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "no", ofType: "mp3")!)
        do{
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)

        } catch {
        print("there was some error. The error was \(error)")
        }
         audioPlayer.play()
        }
        else if (magicBall.image?.isEqual(UIImage(named: "theanswerisyes")))! {
            let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "theanswerisyes", ofType: "mp3")!)
        do{
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)

        } catch {
        print("there was some error. The error was \(error)")
        }
         audioPlayer.play()
        }
        else if (magicBall.image?.isEqual(UIImage(named: "noidea")))! {
            let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "noidea", ofType: "mp3")!)
        do{
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)

        } catch {
        print("there was some error. The error was \(error)")
        }
         audioPlayer.play()
        }
        else if (magicBall.image?.isEqual(UIImage(named: "askagainlater")))! {
            let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "askagainlater", ofType: "mp3")!)
        do{
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)

        } catch {
        print("there was some error. The error was \(error)")
        }
         audioPlayer.play()
        }

    }

    }

你的代码真乱。 首先,我建议你做一个播放声音的函数:

func playSound(fileName: String, fileType: String) {

       let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: fileName,     ofType: fileType)!)

        do{
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)

        }catch {
            print("there was some error. The error was \(error)")
        }
        audioPlayer.play()
}

你必须有第一次播放声音的回调。完成第一个声音后,你可以检查你的 if-else 或者你可以尝试 switch-case。

此外,您可以使用延迟来播放第二个声音

我创建了一个新项目并将您的代码更改为:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBOutlet weak var magicBall: UIImageView!
    // you never used this
    //var magicBallDisplay = 1
    var audioPlayer = AVAudioPlayer()
    override func viewDidLoad() {
        super.viewDidLoad()
        magicBall.image = #imageLiteral(resourceName: "theanswerisyes")
    }

    @IBAction func askButtonPressed(_ sender: UIButton) {
        // because you have audio file and image with equal name i made array of string
        let magicBallArray = [ "yes","no","theanswerisyes","noidea","askagainlater"]
        // check if i get not null item
        guard let choosedImageName = magicBallArray.randomElement() else {return}
        print(choosedImageName)
        // set image with random picked name
        magicBall.image = UIImage(named: choosedImageName)
        // play ask sound
        playSound(fileName: "Ask", fileType: "wav")
        // play picked image sound after 10 second from now()
        // change number to your needed time
        DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
            self.playSound(fileName: choosedImageName, fileType: "mp3")
        })
    }

    private func playSound(fileName: String, fileType: String)
    {
        // check if you find the audio file
        guard let url = Bundle.main.path(forResource: fileName, ofType: fileType) else {
            print("path not found")
            return
        }
        // make NSURL from path
        let soundURL = NSURL(fileURLWithPath: url)

        do{
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)

        } catch {
            print("there was some error. The error was \(error)")
        }
        audioPlayer.play()
    }
}

我给你解释代码。 我没有启用按钮。当你在 swift

中变得更强时,你可以改进此代码