2015-06-11 28 views
6

對於我的iPhone應用程序的var testAudio聲明,我收到一個錯誤這裏AVAudioPlayer不再雨燕2.0的工作/ Xcode的7測試版

「呼叫可以拋出,但錯誤不能拋棄的屬性初始化的」

import UIKit 
import AVFoundation 
class ViewController: UIViewController { 
    var testAudio = AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource("testAudio", ofType: "wav")!), fileTypeHint:nil) 

當我轉移到Xcode 7測試版時發生這種情況。

我怎樣才能讓這個音頻剪輯在Swift 2.0中運行?

回答

21

斯威夫特2有一個全新的錯誤處理系統,你可以在這裏閱讀更多關於它:Swift 2 Error Handling

在你的情況下,構造函數AVAudioPlayer可能會引發錯誤。 Swift不會讓你使用在屬性初始值設定項中拋出錯誤的方法,因爲在那裏沒有辦法處理它們。相反,不要初始化屬性,直到視圖控制器的init

var testAudio:AVAudioPlayer; 

init() { 
    do { 
     try testAudio = AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource("testAudio", ofType: "wav")!), fileTypeHint:nil) 
    } catch { 
     //Handle the error 
    } 
} 

這給你一個機會來處理創建音頻播放器時可能出現的任何錯誤,並停止Xcode給你警告。

+0

我相信;在這裏不需要 – cmario

+1

如何獲得AVAudioPlayer拋出的實際錯誤? –

2

如果你知道一個錯誤將不會退還您可以添加試試!事先:

testAudio = try! AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource 
1

對我的作品在雨燕2.2

但是不要忘了給FILENAME.MP3添加到項目構建phases->複製包資源(右鍵單擊該項目的根)

var player = AVAudioPlayer() 

func music() 
{ 

    let url:NSURL = NSBundle.mainBundle().URLForResource("fileName", withExtension: "mp3")! 

    do 
    { 
     player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil) 
    } 
    catch let error as NSError { print(error.description) } 

    player.numberOfLoops = 1 
    player.prepareToPlay() 
    player.play() 

}