2016-07-28 157 views
2

如何聲明AKAudioPlayer用AKAudioPlayer播放聲音 - iOS

我使用AudioKit Lib,我只需要幫助打.wav文件與更改文件按鈕。

import UIKit 
    import AudioKit 

    class ViewController: UIViewController { 

      let file = NSBundle.mainBundle().pathForResource("song", ofType: "wav") 
      let song = AKAudioPlayer(file!) // <--- ERROR = instance member 'file' cannot be used on type 

      override func viewDidLoad() { 
       super.viewDidLoad() 

       AudioKit.output = song 
       AudioKit.start() 

       song.play() 
      } 


      @IBAction func btn(sender: AnyObject) { 

       song.replaceFile("NewFile") 
       song.play() 

      } 

     } 

回答

2

這是一個非常快速的解決您的問題。它可以做得更好,但至少你可以得到這個想法。

首先嚐試使用函數創建一個新類,以播放您的文件,然後使用另一個函數重新載入您的新替換文件。

class PlayMyMusic { 
    var songFile = NSBundle.mainBundle() 
    var player: AKAudioPlayer! 

    func play(file: String, type: String) -> AKAudioPlayer { 
    let song = songFile.pathForResource(file, ofType: type) 
    player = AKAudioPlayer(song!) 
    return player 
    } 

    func rePlay(file: String, type: String, curPlay: AKAudioPlayer) { 
    let song = songFile.pathForResource(file, ofType: type) 
    curPlay.stop() 
    curPlay.replaceFile(song!) 
    curPlay.play() 
    } 
} 

啓動類視圖中

class testViewController: UIViewController { 

    let doPlay = PlayMyMusic().play("A", type: "wav") 
    ......... 
    ......... 

發揮你的音樂你的視圖內

override func viewDidLoad() { 
    super.viewDidLoad() 

    AudioKit.output = self.doPlay 
    AudioKit.start() 
    doPlay.looping = true 
    doPlay.play() 

} 

然後,當你要重新加載一個新的文件中使用回放功能

@IBAction func btn(sender: AnyObject) { 
    PlayMyMusic().rePlay("C", type: "wav", curPlay: self.doPlay) 

} 
+1

非常感謝你 – EssamSoft

+1

不客氣! –