如何在Swift 2中播放声音文件

时间:2016-01-06 13:05:53

标签: swift audio

我使用下面的代码,但没有听到声音。

var audioPlayer:AVAudioPlayer?

override func viewDidLoad() {

    super.viewDidLoad()

    let path = NSBundle.mainBundle().pathForResource("SecondBeep", ofType: "wav")
    let url = NSURL.fileURLWithPath(path!)

    do {
        try audioPlayer = AVAudioPlayer(contentsOfURL: url)
    } catch {
        print("Player not available")
    }
    audioPlayer?.prepareToPlay()
    audioPlayer?.play()

}

正确导入AVFoundation,并将声音文件添加到项目中。检查了其他stackoverflow主题,但它没有帮助。

尝试更改为URLForResource,但也没有帮助。

    let path = NSBundle.mainBundle().URLForResource("SecondBeep", withExtension: "wav")
    let url = NSURL.fileURLWithPath(path!.path!)

如何解决问题?

2 个答案:

答案 0 :(得分:5)

import UIKit
import AVFoundation
class ViewController: UIViewController {
    var audioPlayer:AVAudioPlayer!
    override func viewDidLoad() {
        super.viewDidLoad()
        if let myAudioUrl = NSBundle.mainBundle().URLForResource("SecondBeep", withExtension: "wav") {
            do {
                audioPlayer = try AVAudioPlayer(contentsOfURL: myAudioUrl)
                audioPlayer.prepareToPlay()
                audioPlayer.play()
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

答案 1 :(得分:1)

import UIKit
import AVFoundation
class ViewController: UIViewController {

  var audioPlayer: AVAudioPlayer!  // Global variable

    override func viewDidLoad()
    {
        super.viewDidLoad()

        playVes()


        // Do any additional setup after loading the view, typically from a nib.
    }

    func playVes() {
        do {
            self.audioPlayer =  try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("123", ofType: "mp3")!))
            self.audioPlayer.play()

        } catch {
            print("Error")
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}