我正在尝试从一组声音中创建一个包含4个项目的随机播放列表,用户可以播放/暂停,向前跳过,然后向后跳过。
我对Swift和面向对象编程都很陌生(抱歉!)。目前正在使用Xcode 7.3.1。
我的代码:
class ViewController: UIViewController {
var E1Audio: AVPlayerItem?
var E2Audio: AVPlayerItem?
var E3Audio: AVPlayerItem?
var E4Audio: AVPlayerItem?
var E5Audio: AVPlayerItem?
var E6Audio: AVPlayerItem?
struct playlist {
var initialitems: [AVPlayerItem] = []
var shuffleditems: [AVPlayerItem] {
initialitems.shuffle
}
var instanceplaylist: [AVPlayerItem]{
shuffleditems[0...3]
}
}
var EnvPlaylist: [AVPlayerItem] = playlist(initialitems: [E1Audio, E2Audio, E3Audio, E4Audio, E5Audio, E6Audio])
let EnvPlayer = AVPlayer()
var currentTrack = 0
@IBAction func envPreviousTrack() {
if currentTrack-1 < 0 {
currentTrack = (EnvPlaylist.count - 1) < 0 ? 0 : (EnvPlaylist.count - 1)
} else {
currentTrack-1
}
}
@IBAction func envNextTrack() {
if currentTrack+1 > EnvPlaylist.count {
currentTrack = 0
} else {
currentTrack+1;
}
}
@IBAction func envPlayTrack() {
if EnvPlaylist.count > 0 {
EnvPlayer.replaceCurrentItemWithPlayerItem(InstancePlaylist2[currentTrack])
EnvPlayer.play()
override func viewDidLoad() {
super.viewDidLoad()
let E1Audio = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("E1Audio", withExtension: "wav")!)
let E2Audio = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("E2Audio", withExtension: "wav")!)
let E3Audio = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("E3Audio", withExtension: "wav")!)
let E4Audio = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("E4Audio", withExtension: "wav")!)
let E5Audio = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("E5Audio", withExtension: "wav")!)
let E6Audio = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("E6Audio", withExtension: "wav")!)
}
}
}
这给出了错误:实例成员&#39; E1Audio&#39;不能在类型&#39; ViewController&#39;。
上使用如果我将EnvPlaylist的声明移动到viewDidLoad(),那么我无法在类级别定义函数envPreviousTrack(),envNextTrack()和envPlayTrack(),然后链接到我的UI按钮。 / p>
我该如何解决这个问题?提前致谢。对不起,如果这是一个愚蠢的问题。
答案 0 :(得分:0)
你不能直接声明这样的变量。这样做:
class ViewController: UIViewController {
var E1Audio = AVPlayerItem()
override func viewDidLoad() {
super.viewDidLoad()
E1Audio = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("E1Audio", withExtension: "wav")!)
}
}
对所有音频项重复此操作。