声音与UIAlert / UIAlertController

时间:2019-01-10 04:21:46

标签: swift xcode audio uialertcontroller

嗨,我想知道是否可以使用UIAlert播放声音?根据以下文章,这似乎是可能的,但是我正在努力将Obj-C转换为Swift。任何帮助表示赞赏!

IOS alert message with sound

1 个答案:

答案 0 :(得分:1)

这是您快速实现它的方法。

首先,如果您关注问题中包含的帖子,则需要在viewWillAppear中执行该操作。

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

var audioPlayer: AVAudioPlayer?

然后从URL分配Bundle

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