【发布时间】:2019-01-10 04:21:46
【问题描述】:
您好,我想知道是否可以使用 UIAlert 播放声音?根据以下帖子,这似乎是可能的,但我正在努力将 Obj-C 翻译成 Swift。任何帮助表示赞赏!
【问题讨论】:
标签: swift xcode audio uialertcontroller
您好,我想知道是否可以使用 UIAlert 播放声音?根据以下帖子,这似乎是可能的,但我正在努力将 Obj-C 翻译成 Swift。任何帮助表示赞赏!
【问题讨论】:
标签: swift xcode audio uialertcontroller
这是您可以快速实现它的方法。
如果您关注问题中包含的帖子,首先您需要在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)
}
}
【讨论】: