【问题标题】:How to add a delay to a sound being played with swift如何为快速播放的声音添加延迟
【发布时间】:2020-01-13 16:25:18
【问题描述】:

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

但是现在当按下按钮时应该播放的声音只播放一次,从那里我只听到每个图像显示的声音。这是因为我在“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()
        }

    }

    }

【问题讨论】:

    标签: ios swift audio uiimageview delay


    【解决方案1】:

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

    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 中变得更强大时,你可以改进这段代码

    【讨论】:

    • ImanMF - 非常感谢您不厌其烦地向我解释这一点。现在很清楚如何解决这个问题,并且我将来可以使用它。非常感谢。
    • @MarcBaier swift 具有可空性,您必须使用 if 和 guard 语句来练习。
    【解决方案2】:

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

    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。

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

    【讨论】:

    • 非常感谢您的提示。由于我是初学者,我真的不知道哪些部分会被这个新功能取代。如何设置它以便新的“playSound”函数调用/播放正确/对应的声音?
    猜你喜欢
    • 2011-05-09
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多