2016-04-24 68 views
0

我有這個文件,並希望在另一個類中使用此文件,但這不起作用。我認爲這是因爲我沒有在這個文件中初始化AVAudioPlayer,所以我解決了這個問題,但是出現了一條消息,說"Call can throw, but it is not marked with 'try' and the error is not handled"我的實現不成功。我不知道如何處理這個問題。你能指出初始化有什麼問題,並提供一些可用的代碼。提前致謝。如何在Swift中初始化AVAudioPlayer

class SoundManager: AVAudioPlayer { 
var _Sound: AVAudioPlayer! 

override init() { 
    let url = NSBundle.mainBundle().URLForResource("rain", withExtension: "wav") 
    super.init(contentsOfURL: url!) 
} 

func playSound() { 


    if (url == nil) { 
     print("Could not find the file \(_Sound)") 
    } 

    do { 
     _Sound = try AVAudioPlayer(contentsOfURL: url!, fileTypeHint: nil) 

    } 
    catch let error as NSError { print(error.debugDescription) 

    } 
    if _Sound == nil { 
     print("Could not create audio player") 
    } 
    _Sound.prepareToPlay() 
    _Sound.numberOfLoops = -1 
    _Sound.play() 
} 

} 

回答

1

我推薦使用這種方式init你管理器,它不必是AVAudioPlayer的子類。

 
class SoundManager { 
    var _Sound: AVAudioPlayer! 
    var url: NSURL? 

    /** 
    init with file name 

    - parameter fileName: fileName 

    - returns: SoundManager 
    */ 
    init(fileName: String) { 
     url = NSBundle.mainBundle().URLForResource(fileName, withExtension: "wav") 
    } 

    func playSound() { 
     if (url == nil) { 
      print("Could not find the file \(_Sound)") 
     } 

     do { 
      _Sound = try AVAudioPlayer(contentsOfURL: url!, fileTypeHint: nil) 

     } 
     catch let error as NSError { print(error.debugDescription) 

     } 
     if _Sound == nil { 
      print("Could not create audio player") 
     } 
     _Sound.prepareToPlay() 
     _Sound.numberOfLoops = -1 
     _Sound.play() 
    } 
} 

使用 let manager = SoundManager(fileName: "hello") manager.playSound()

+0

工作!我認爲實現AVAuiodPlayer作爲一個子類是必要的。我很好奇在什麼情況下,我應該使用它嗎? – bagels

+0

@ryohei當你想使用這個管理器作爲AVAudioPlayer,然後使用子類。它將衝破超類的性質和功能。當涉及到管理類時,我更喜歡創建沒有子類的類,並且像在'var _Sound:AVAudioPlayer!'行那樣爲它創建一個AVAudioPlayer的實例。不要忘記標記我的答案是有用的~~ – BrikerMan

+0

哦,我明白了。我很高興解決這個問題!感謝您的回答 :) – bagels