簡體   English   中英

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

[英]How to Play Sound File in Swift 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!)

我該如何解決該問題?

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


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM