2016-07-28 162 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

不客气! –