How to get the duration of an MP3 file in Android

2020-06-23 07:30发布

I am working on a media player project and I want to rotate an image according to the length of the MP3 file that I am playing, i.e. the image should stop rotating when the song is ended. I want to get the duration of the selected MP3 file so I can time the rotation.

I read this question Get PCM data from an MP3 file in Android but I couldn't see how to read the song duration. How can I do this is there - is any function or methods to get the duration of the file?

1条回答
Deceive 欺骗
2楼-- · 2020-06-23 07:54

Here is the Kotlin version

            var metaRetriever:MediaMetadataRetriever = MediaMetadataRetriever()
            metaRetriever.setDataSource(filePath)

            var out:String = ""
            var txtTime:String = ""

            var duration:String = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)

            Log.d("DURATION VALUE", duration)

            var dur:Long = duration.toLong()
            var seconds:String = ((dur % 60000)/1000).toString()

            Log.d("SECONDS VALUE", seconds)

            var minutes:String = (dur / 60000).toString()
            out = minutes + ":" + seconds

            if (seconds.length == 1){
                txtTime = "0" + minutes + ":0" + seconds
            }
            else {
                txtTime = "0" + minutes + ":" + seconds
            }

            Log.d("MINUTES VALUE", minutes)

            Log.d("FORMATTED TIME", txtTime)

            metaRetriever.release()
查看更多
登录 后发表回答