【问题标题】:Play Sound Using AVFoundation with Swift 2在 Swift 2 中使用 AVFoundation 播放声音
【发布时间】:2015-12-25 07:30:29
【问题描述】:

我正在尝试使用 AVFoundation 在我的 iOS 应用(用 Swift 2 编写)中播放声音。我让它与以前版本的 Swift 没有任何问题。我正在使用 Xcode 7.0。我不确定问题是什么,也找不到关于 Swift 2 播放声音的任何其他信息。这是我的声音部分的代码:

import AVFoundation

class ViewController: UIViewController {
    var mySound = AVAudioPlayer()

    override func viewDidLoad() {
            super.viewDidLoad()
        mySound = self.setupAudioPlayerWithFile("mySound", type:"wav")

        mySound.play()
    }

    func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer  {
            var path = NSBundle.mainBundle().pathForResource(file, ofType:type)
            var url = NSURL.fileURLWithPath(path!)

            var error: NSError?

            var audioPlayer:AVAudioPlayer?
            audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)

            return audioPlayer!
    }
}

我收到此错误,但感觉可能还有其他问题:

'NSString' 不能隐式转换为 'String';您的意思是使用 'as' 来显式转换吗?

【问题讨论】:

标签: swift avfoundation swift2


【解决方案1】:

您需要实现 do try catch 错误处理。试试这样:

func setupAudioPlayerWithFile(file: String, type: String) -> AVAudioPlayer? {

    if let url = NSBundle.mainBundle().URLForResource(file, withExtension: type) {
        do {
            return try AVAudioPlayer(contentsOfURL: url)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    return nil
}

【讨论】:

    【解决方案2】:

    就像狮子说的那样

    你需要实现 do try catch 错误处理。

    这是另一个在按下按钮时会发出声音的代码示例。

    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
    
    
    @IBAction func play(sender: AnyObject) {
    
         player.play()
    
    }
    
    @IBAction func pause(sender: AnyObject) {
    
        player.pause()
    
    }
    
    
    var player: AVAudioPlayer = AVAudioPlayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let audioPath = NSBundle.mainBundle().pathForResource("sound", ofType: "mp3")!
    
        do {
    
            try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
    
    
        } catch {
    
            // Process error here
    
        }
    
    
      }
    
    }
    

    我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 2014-12-22
      相关资源
      最近更新 更多