2016-01-06 36 views
2

我使用下面的代碼,但聽不到聲音。如何播放聲音文件在斯威夫特2

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!) 

我怎樣才能解決這個問題?

+0

你能更具體,以「不工作」?你的意思是說它不玩? – Arc676

+0

爲什麼不簡單地使用URLForResource而不是pathForResource? –

+0

@ Arc676,聽不到任何東西。我看到打印文件和控制檯中的播放器,但沒有聽到。 –

回答

4
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. 
    } 
} 
+0

謝謝。我創建了一個新項目並添加了聲音文件,實際上您的代碼在Simulator中工作。但是,當我將應用程序發送到iPhone 6s Plus時,它不起作用。關於這個問題的任何想法?在手機應用程序中播放本地文件是安全還是權限問題? –

+0

好的,我必須接受你的答案,因爲它與模擬器一起工作。仍然無法在我的iPhone上工作。 –

+0

@JohnBernard如果不弄清楚,請讓我知道 –

3
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. 
    } 


} 
+0

@BalajiGupta,這基本上是我的代碼相同,不是嗎? –

+1

這是Swift 1代碼,不是Swift 2! OP的代碼示例在Swift 2中......這樣一個糟糕的答案如何得到提升?唉... – Moritz

+0

我已經改變... N它在我的身邊工作.. –