如何在进入屏幕时自动播放音频

How to automatically play audio when entering a screen

我正在学习 Swift,我正在通过构建一个应用程序来强迫自己学习这门语言,从而使自己陷入困境。我想要实现的是,当我从屏幕 1 转移到屏幕 2 时,无需执行任何操作即可播放音频。音频是 A-14a。下面的代码已设置为当我单击“方向”按钮时,它会播放音频,但我不知道如何立即执行。下面的图片有助于说明我的意思。

1st Screen 2nd Screen

我的代码如下:

import UIKit
import AVFoundation

class Intervention_Numerals1: UIViewController {


    @IBOutlet weak var Directions: UIButton!
    @IBOutlet weak var Done: UIButton!
    var audioPlayer = AVAudioPlayer()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpElements()
        //Audio Test
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "A-N14a", ofType:"mp3")!))
            audioPlayer.prepareToPlay()
        } catch {
            print(error)
        }
    }
    
    func setUpElements() {
        // Style the elements
        Utilities.styleFilledButton(Directions)
        Utilities.styleFilledButton(Done)
    }

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

请告诉我有关如何执行此操作的任何建议

使用这个方法

 override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
         audioPlayer.play()
    }

您可以重写几个方法来了解视图控制器的状态,并在该状态出现时向 运行 添加代码。

正如 Amila 所说,您正在寻找的可能是 viewDidAppear, 另一种可能也可以帮助您实现这一目标的方法是 viewWillAppear

我将在下面提供其中大部分方法的代码以及它们的作用,以便您可以尝试所有方法并进行试验:

override func viewDidLoad() {
    //This is what you already use every time, its called when the VC's view is loaded into memory
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    //This happens when the view is *about* to appear, it happens before users see anything from the view, great for updating UI 
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    //This happens when the view actually appears on screen and when all the animations of loading the View Controller are over. 
    //not so good for updating UI since users will see a glimpse of previous view data.
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    //This happens when the view is *about* to disappear, great example for this is when you begin swiping to go back in a navigation controller.
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    //This happens when view is no longer on screen for user to see, like when that swiping back animation in using navigation controller is *finished*
}

当您的 View Controller 中的视图发生变化时,还会出现其他一些情况,例如 viewWillLayoutSubviewsviewDidLayoutSubviews

使用所有这些来控制何时发生,希望这对您有所帮助:)