[英]Swift 2 - AVAudioPlayer not playing audio
我正在嘗試使用AVAudioPlayer播放聲音,但無法播放。 我嘗試了設備(iPhone 6s)和模擬器。 我沒有收到任何錯誤,它記錄了它的播放。 當我在audioPlayer.play()之前設置斷點並越過它時,它會播放幾秒鍾,然后停止。 我的代碼:
let soundURL = NSBundle.mainBundle().URLForResource("test", withExtension: "mp3")
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
if let soundURL = soundURL {
let audioPlayer = try AVAudioPlayer(contentsOfURL: soundURL)
audioPlayer.volume = 1
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
print(audioPlayer.duration)
audioPlayer.play()
print("PLAYED")
}
}catch {
print("Error getting the audio file")
}
這是一個有效的例子。 我不確定相對於其余代碼,您在何處具有上面顯示的代碼。 確保您的設備音量未處於靜音狀態且已打開...
//declare these as instance variables
var AudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("FileName", ofType: "mp3")!)
var AudioPlayer = AVAudioPlayer()
//inside viewDidLoad establish your AVAudioSession and configure the AudioPlayer with the contents of URL
override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
//print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
//print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
do {
try AudioPlayer = AVAudioPlayer(contentsOfURL: AudioURL, fileTypeHint: nil)
} catch {
print("errorin do-try-catch")
}
}
//play audio
@IBAction func playAudio(sender: AnyObject){
AudioPlayer.play()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.