vendredi 20 mai 2016

Swift 2.2: creating random playlist for AVAudioPlayer

I am trying to create a random playlist of 4 items from a bank of sounds that the user is able to play/pause, skip forwards, and skip backwards through.

I'm new to both Swift and object-orientated programming (sorry!). Currently using Xcode 7.3.1.

My code:

class ViewController: UIViewController {

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")!)

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()       
    }
}
}

This gives the error: instance member 'E1Audio' cannot be used on type 'ViewController'.

If I move the declaration of EnvPlaylist to viewDidLoad() then I'm unable to define the functions envPreviousTrack(), envNextTrack(), and envPlayTrack() at the class level to then link to my UI buttons.

How can I get around this? Thanks in advance. Sorry if it's a dumb question.




Aucun commentaire:

Enregistrer un commentaire