Hi @JoeKun. I'm delighted to hear that Apple are now engaging more on the forums. I have in the past submitted polite, fully constructed Feedback Assistant reports related to the playback performance of Apple Music and so far been met with silence. I hope to hear back soon. During the months of development, I've read countless posts on these and other forums from other developers facing what sound like exactly the same bugs, spread over several years, during which time sadly no fixes seem to have been forthcoming. I can only hope that at some point there is a concerted effort within Apple to improve the implementation's reliability. No more "failed to prepare to play"!
So far, nobody has directly answered the OP's question. This is the primary issue here: Detecting end of playback.
It kinda "feels" like people dancing around admitting that it's impossible, at least cleanly. For whatever reason, when the Apple Music API finishes playing a track and there's nothing else in a playlist, it performs the very strange behaviour of entering a paused state and seeking to the start offset of either the first playlist track, or the last playlist track (LATER EDIT: I also do see sometimes behaviour where current position is reported as fractionally after the end of the track, too). I've never been too clear on this because none of its behaviour in this regard appears to be described in the API documentation, so we have to guess and use observation, leaving developers with no idea if they're relying upon behaviour that's meant to be part of the API's contract between implementation and consumer, or just a random observed quirk.
There is a "stopped" state for the media player, but it does not enter this state. Consequently, distinguishing between a user initiated pause event or an "actually I stopped playing" pause event, or a "user initiated pause then the user scrubbed a position slider back to the start of the track" edge case thus takes time-consuming coding effort and heuristic fudging, all because the API doesn't enter a stopped state.
At the risk of mentioning a second item and building a laundry list, it'd also be lovely if we could set playback volume for our applications. This used to be possible, but then the ability was removed.
It's really quite surprising to me that in 2021 we might be using a media playback API where reliably detecting end of playback is very difficult, and setting playback volume is impossible. I really hope that these matters can be addressed with haste.