我使用下面的代码,但没有听到声音.
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()
}
Run Code Online (Sandbox Code Playgroud)
正确导入AVFoundation并将声音文件添加到项目中.检查了其他stackoverflow主题,但它没有帮助.
试图改变,URLForResource但也没有帮助.
let path = NSBundle.mainBundle().URLForResource("SecondBeep", withExtension: "wav")
let url = NSURL.fileURLWithPath(path!.path!)
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
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.
}
}
Run Code Online (Sandbox Code Playgroud)