如何声明AKAudioPlayer
?
我正在使用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()
}
}
这是一个非常快速的问题解决方案。它可以做得更好,但至少你能明白。
首先尝试创建一个新类,其中包含一个函数来播放您的文件,然后使用另一个函数像这样重新加载您的新替换文件。
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)
}
查看AudioKit游乐场
更新
AKAudioPlayer已弃用,请使用AudioPlayers指令并查看AudioKit v5迁移指南