首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AVFoundation播放声音swift 2

AVFoundation播放声音swift 2
EN

Stack Overflow用户
提问于 2015-09-29 06:47:02
回答 2查看 809关注 0票数 1

如果我写“try”而不写“!”,我会尝试用Swift 2.0播放声音。我得到了错误“抛出的错误没有处理”,AVAudioPlayer不是可选的为什么Xcode请求'try!‘如果我写“尝试!”我的应用程序崩溃“在解包可选值时意外发现nil”

代码语言:javascript
复制
class TouchViewController: UIViewController {
var soundPath:NSURL? 
...................
 //Play Bipsound
        do { soundPath = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Bipsound", ofType: "wav")!)
           var sound = try! AVAudioPlayer(contentsOfURL: soundPath!, fileTypeHint: nil)
            sound.prepareToPlay()
            sound.play() }
EN

回答 2

Stack Overflow用户

发布于 2015-09-29 07:42:45

代码语言:javascript
复制
    var soundPath:NSURL? 

    if let path = Bundle.main.path(forResource: "Bipsound", ofType: "wav") {
        soundPath = NSURL(fileURLWithPath: path)
        do {
            let sound = try AVAudioPlayer(contentsOfURL: soundPath!, fileTypeHint:nil)
            sound.prepareToPlay()
            sound.play()
        } catch {
            //Handle the error
        }
    }
票数 3
EN

Stack Overflow用户

发布于 2015-09-29 07:49:37

假装你以前从未见过Swift中的!强制解包操作符,并完全停止使用它。它基本上就是“如果这个可选的包含nil,就会崩溃”操作符。使用"if let“样式的可选绑定或try/catch,就像@LLooggaann在他的优秀答案中所概述的那样。(已投票)

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32832976

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档