Swift 使用UIAlert/UIAlertController发出声音

Swift 使用UIAlert/UIAlertController发出声音,swift,xcode,audio,uialertcontroller,Swift,Xcode,Audio,Uialertcontroller,嗨,我想知道是否可以用UIAlert播放声音?根据下面的帖子,这似乎是可能的,但我正在努力将Obj-C翻译成Swift。感谢您的帮助 以下是您在swift中实现这一目标的方法 首先,如果您正在关注问题中包含的帖子,您需要在视图中执行该操作 然后创建音频播放器,播放您的声音,如下所示: var audioPlayer: AVAudioPlayer? 然后从Bundle let resourcePath = Bundle.main.resourcePath let stringURL = reso

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


以下是您在swift中实现这一目标的方法

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

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

var audioPlayer: AVAudioPlayer?
然后从
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)
    }
}

这不太管用,所以我修改了代码,让url=Bundle.main.url(forResource:“disconnect”,带扩展名:“wav”)self.audioPlayer=try?AVAudioPlayer.init(contentsOf:url!,fileTypeHint:AVFileType.wav.rawValue)self.audioPlayer?.numberOfLoops=1现在它工作得很好。谢谢你的帮助!你没有提供那么多信息。很高兴帮助你……)道歉没说清楚。由于某些原因,您获取声音文件URL的方法不起作用,但也没有使应用程序崩溃。。。奇怪。。