If you want to use the music library, you need to allow access to the music library.
info.plist
Privacy - Media Library Usage Description
To play a song, use MediaPlayer to get the song from your music library and
You can play it by dividing it into MPMediaItemCollection.
python
import MediaPlayer
In addition to songs, you can also get a list from albums and artists from the music library.
python
//Get a list of songs
let mPMediaQuery = MPMediaQuery.songs()
//Get a list of albums
let mPMediaQuery = MPMediaQuery.albums()
//Get a list of artists
let mPMediaQuery = MPMediaQuery.artists()
After you get a song, you need to separate it for each song to play.
python
let mPMediaQuery = MPMediaQuery.songs()
if let collections = mPMediaQuery.collections {
for collection in collections {
//title
print(collection.items[0].title!)
}
}
You can specify and play songs in music with setQueue (with: MPMediaItemCollection).
python
var player = MPMusicPlayerController.applicationMusicPlayer
//Set a song
player.setQueue(with: MPMediaItemCollection)
//Allow the song to play
player.prepareToPlay()
python
player.play()
python
player.pause()
python
player.stop()
You can change the repeat method depending on the setting value.
//User favorite repeat
player.repeatMode = .default
//Do not repeat
player.repeatMode = .none
//Repeat the current song
player.repeatMode = .one
//Repeat current playlist
player.repeatMode = .one
You can change the shuffle method depending on the setting value.
//Do not shuffle
player.shuffleMode = .off
//User favorite shuffle
player.shuffleMode = .default
//Shuffle for each song
player.shuffleMode = .songs
//Shuffle for each album
player.shuffleMode = .albums
https://developer.apple.com/documentation/mediaplayer/mpmusicplayercontroller
Recommended Posts