你的结构嵌套在结构中嵌套在结构中很奇怪,反正我不知道你的想法。
请测试一下:
class MyModel: Codable {
var feelSongs: [MyModel.M.A] = [
MyModel.M.A.init(id: 1, afcontent: "Feeling Happy", aURL: "a1.mp3", isOn: true),
MyModel.M.A.init(id: 2, afcontent: "Feeling Sad", aURL: "a2.mp3", isOn: true),
MyModel.M.A.init(id: 3, afcontent: "Feeling Positive", aURL: "a3.mp3", isOn: true),
MyModel.M.A.init(id: 4, afcontent: "Feeling Healthy", aURL: "a4.mp3", isOn: true)
]
struct M: Codable{
var mURL: String
var bgMusic : String
var bgVol : Double
struct A : Codable, Identifiable {
var id : Int
var afcontent : String
var aURL : String
var isOn : Bool
}
}
}
class MyViewModel: ObservableObject {
@Published var isPlaying = false
var player = AVAudioPlayer()
var theModel = MyModel()
**//ADDED THIS**
var playNow = 0
func play(){
if playNow >= theModel.feelSongs.count {
return
}
let url = theModel.feelSongs[playNow]
guard let url = URL(string: url) else {
return
}
**//ADDED THIS**
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: item)
do {
player = try AVAudioPlayer(contentsOf: url )
if player.isPlaying{player.pause()}
else{player.play()}
isPlaying = player.isPlaying
}
catch{print("error")}
}
**//ADDED THIS**
func playerDidFinishPlaying(note: NSNotification) {
play()
}
}
//
struct ContentView: View {
var mymodel = MyViewModel()
var body: some View {
//Text("3")
List(mymodel.theModel.feelSongs) { song in
Text(song.afcontent)
}
.onAppear {
mymodel.play()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}