使用 UIAlert / UIAlertController 发声

Sound with UIAlert / UIAlertController

您好,我想知道是否可以使用 UIAlert 播放声音?根据以下post似乎是可能的,但我正在努力将Obj-C翻译成Swift。感谢您的帮助!

IOS alert message with sound

这是您可以在 swift 中实现的方法。

首先,如果您遵循问题中包含的 post,则需要在 viewWillAppear 中执行该操作。

然后创建 audioPlayer 来播放您的声音,如下所示:

var audioPlayer: AVAudioPlayer?

然后从 Bundle

分配 URL
let resourcePath = Bundle.main.resourcePath
let stringURL = resourcePath! + "foo.mp3"
let url = URL.init(fileURLWithPath: stringURL)

然后在您的警报出现之前播放它:

audioPlayer?.play()

现在像这样创建您的警报:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { action in
    self.audioPlayer?.stop()
 }))

 audioPlayer?.play()
 self.present(alert, animated: true, completion: nil)

你的完整代码将是:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer: AVAudioPlayer?

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

    override func viewWillAppear(_ animated: Bool) {

        let resourcePath = Bundle.main.resourcePath
        let stringURL = resourcePath! + "foo.mp3" //change foo to your file name you have added in project
        let url = URL.init(fileURLWithPath: stringURL)

        audioPlayer = try? AVAudioPlayer.init(contentsOf: url)
        audioPlayer?.numberOfLoops = 1

        let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { action in
            self.audioPlayer?.stop()
        }))

        audioPlayer?.play()
        self.present(alert, animated: true, completion: nil)
    }
}