我有类似的问题,如:

  • How do I get the lyrics of the currently playing song in Swift 4?-这里没有答案
  • iPhone song lyrics access-答案无效
  • How to get lyrics for Now Playing song in iOS10 (Swift 3)-答案无效

  • 我需要获取当前正在播放的歌曲的歌词。

    如果我只是尝试从媒体项目获取歌词,则会得到空结果:
    let musicPlayerController = MPMusicPlayerController.systemMusicPlayer
    
    // ...
    
    if let nowPlayingItem = musicPlayerController.nowPlayingItem {
        // We have empty string here
        if let lyrics = nowPlayingItem.lyrics {
            print("Lyrics: \(lyrics)")
        }
    }
    

    我试图按照上面答案中的建议通过资产网址获取歌词,但它不起作用,资产网址始终为零。
    let musicPlayerController = MPMusicPlayerController.systemMusicPlayer
    
    // ...
    
    if let nowPlayingItem = musicPlayerController.nowPlayingItem {
        if let songUrl = nowPlayingItem.value(forProperty: MPMediaItemPropertyAssetURL) as? URL {
            print("song url: \(songUrl)")
            let songAsset = AVURLAsset(url: songUrl)
    
            if let lyricsFromAsset = songAsset.lyrics {
                print("Lyrics from asset: \(lyricsFromAsset)")
            }
        }
    }
    

    我也尝试了没有成功(也相应地得到nil和空字符串):
    print("asset url: \(nowPlayingItem.assetURL)")
    print("lyrics from value for property: \(nowPlayingItem.value(forProperty: MPMediaItemPropertyLyrics))")
    

    我完全知道这首歌有歌词,因为我在iPhone上的Apple Music应用中看到了这首歌。我试图为这首歌获得歌词:Queen-Bohemian Rhapsody。

    有人可以帮忙从苹果音乐中获取当前播放歌曲的歌词吗?

    最佳答案

    我们在这里谈论本地文件吗?我不确定它如何与Apple Music文件一起使用,但是对于本地文件,此方法在检索歌词方面具有100%的成功率。

    extension MPMediaItem {
        func lyrics() -> String? {
            guard let url = assetURL else { return nil }
            let ass = AVAsset(url: url)
            return ass.lyrics
        }
    }
    

    10-06 03:20