반응형
import Cocoa
import AVFoundation
import AVKit
//[url] => [AVPlayerItem]: AVPlayerItem.AVAsset.[AVMetadataItem]: AVMetadataItem.AVMetadataKey.String? => [Track] => [Album]
struct Track {
var title: String?
var albumName: String?
var singer: String?
init(aTitle: String?, aAlbumName: String?, aSinger: String?) {
self.title = aTitle
self.albumName = aAlbumName
self.singer = aSinger
}
}
struct Album {
var albumName: String?
var tracks: [Track]
init(aAlbumName: String?, aTracks: [Track]) {
self.albumName = aAlbumName
self.tracks = aTracks
}
}
class TrackManager {
var avPlayerItems: [AVPlayerItem] = []
var albums: [Album] = []
init() {
avPlayerItems = LoadAVPlayerItems() //[AVPlyerItems]
let tracks = LoadTracks()//[Track]
albums = LoadAlbums(tracks: tracks)//[Album]
albums.count
}
func LoadAVPlayerItems() -> [AVPlayerItem] {
let urls = Bundle.main.urls(forResourcesWithExtension: "mp3", subdirectory: nil) ?? []
let playerItems = urls.map{ AVPlayerItem(url: $0) }
return playerItems
}
func LoadTracks() -> [Track] {
let tracks = avPlayerItems.compactMap( {$0.converToTrack()} )
return tracks
}
func LoadAlbums(tracks: [Track]) -> [Album] {
let trackDic = Dictionary(grouping: tracks) { track in
track.albumName
}
var albums: [Album] = []
for track in trackDic {
let album: Album = Album.init(aAlbumName: track.key, aTracks: track.value)
albums.append(album)
}
return albums
}
}
extension AVPlayerItem {
func converToTrack() -> Track {
let metadatas = asset.metadata
var metaTitle: String?
var metaAlbumName: String?
var metaSinger: String?
for meta in metadatas {
if let title = meta.title {
metaTitle = title
}
if let albumName = meta.albumName {
metaAlbumName = albumName
}
if let singer = meta.singer {
metaSinger = singer
}
}
return Track(aTitle: metaTitle, aAlbumName: metaAlbumName, aSinger: metaSinger)
}
}
extension AVMetadataItem {
var title: String? {
guard let title = commonKey?.rawValue, title == "title" else {
return nil
}
return stringValue
}
var albumName: String? {
guard let albumName = commonKey?.rawValue, albumName == "albumName" else {
return nil
}
return stringValue
}
var singer: String? {
guard let singer = commonKey?.rawValue, singer == "singer" else {
return nil
}
return stringValue
}
}
반응형
'iOS > swift' 카테고리의 다른 글
기본문법 (0) | 2021.12.27 |
---|---|
In-Out 파라미터(Parameters) (0) | 2021.11.01 |
[swift] collectionview 사용하기 (0) | 2021.08.21 |
[swift] Access Control (0) | 2021.08.10 |
[swift] view memory 화면 설명 (0) | 2021.08.09 |