How to get the duration of an MP3 file in Android [duplicate]

微笑、不失礼 提交于 2019-12-05 02:30:40

问题


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:


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()


来源:https://stackoverflow.com/questions/9834697/how-to-get-the-duration-of-an-mp3-file-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!