ios - 如何为快速播放的声音添加延迟

标签 ios swift audio uiimageview delay

我是一个完全快速的初学者,正在研究一个教程项目(magic 8 ball),并成功地完成了以下工作: - 按下“询问”按钮时播放特定的声音。 - 对于每个随机挑选的图像播放特定的声音

但是现在,只要按下按钮就应该播放的声音只会播放一次,从那时起我只能听到每个图像显示的声音。这是因为我“卡在”“if - else”循环中吗?或者我是否必须延迟为数组中的每个图像播放的声音?

非常感谢您的帮助!

这是我的代码:

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

    }

    }

最佳答案

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

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 能力更强时,你可以改进这段代码

关于ios - 如何为快速播放的声音添加延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59704751/

相关文章:

ios - 自动续订购买的应用程序拒绝 - 准则 3.1.2 - 业务 - 付款 - 订阅

ios - swift 不能动画 view.origin.y

android - 读取正在播放的本地音频文件的声级以在 Android 中生成 wu-meter

iphone - 如何在 xcode4.3 中获取和修改显示屏幕大小

iphone - UIScrollView和真实内存

ios - iOS/Swift 中的 UI 测试

Swift3 设置父 View 相对于父 View 的约束

c# - 更改C#中的音频格式

audio - 仅使用视频流中的音轨

ios - 您可以使用 iOS6 SDK 构建但在 iPhone 5 上保留信箱吗?