声音AVAudioPlayer无法正常工作

时间:2015-12-08 01:28:19

标签: swift avfoundation avaudioplayer

我正在尝试创建一个使用声音的简单应用。我的AVAudioPlayer函数出错了。

这就是我的意思:

import UIKit
import AVFoundation

class ViewController: UIViewController{
   var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
   super.viewDidLoad()

   var playSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Bell", ofType: "mp3"))

   audioPlayer = AVAudioPlayer(contentsOfURL: playSound, error: &error)

   audioPlayer.play()

}

1 个答案:

答案 0 :(得分:-2)

尝试创建一个单独的功能。 试试这个..

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

    do {
        try audioPlayer = AVAudioPlayer(contentsOfURL: url)
    } catch {
        print("NO AUDIO PLAYER")
    }

    return audioPlayer!
}

然后在任何地方运行audioPlayer.play()。