Skip to content

Commit

Permalink
Merge pull request #2 from samzong/fix/canot-switch-song
Browse files Browse the repository at this point in the history
fix can not switch song after a song end.
  • Loading branch information
samzong authored Sep 18, 2024
2 parents 833ca56 + 039123d commit 088ac39
Showing 1 changed file with 24 additions and 15 deletions.
39 changes: 24 additions & 15 deletions Managers/PlayerManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Foundation
import AVFoundation
import SwiftUI

class PlayerManager: ObservableObject {
class PlayerManager: NSObject, ObservableObject, AVAudioPlayerDelegate {
@Published var playlist: [Track] = []
@Published var currentTrack: Track? {
didSet {
Expand All @@ -24,7 +24,8 @@ class PlayerManager: ObservableObject {
private var player: AVAudioPlayer?
private var currentIndex = 0

init() {
override init() {
super.init()
loadSavedMusicFolder()
}

Expand Down Expand Up @@ -78,21 +79,22 @@ class PlayerManager: ObservableObject {
}

func play() {
guard let track = currentTrack else {
print("No current track to play")
return
}

do {
player = try AVAudioPlayer(contentsOf: track.url)
player?.play()
isPlaying = true
print("Started playing: \(track.title)")
} catch {
print("Could not create player for \(track.title): \(error)")
}
guard let track = currentTrack else {
print("No current track to play")
return
}

do {
player = try AVAudioPlayer(contentsOf: track.url)
player?.delegate = self // 设置代理
player?.play()
isPlaying = true
print("Started playing: \(track.title)")
} catch {
print("Could not create player for \(track.title): \(error)")
}
}

func pause() {
player?.pause()
isPlaying = false
Expand All @@ -112,4 +114,11 @@ class PlayerManager: ObservableObject {
currentTrack = playlist[currentIndex]
play()
}

// AVAudioPlayerDelegate 方法
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if flag {
playNext()
}
}
}

0 comments on commit 088ac39

Please sign in to comment.