解决android MediaPlayer获取不到在线音乐时长

2019-10-11  本文已影响0人  helang1991

前言

最近,开发了一个项目,里面有涉及到了MP3等音频播放的功能,就稍微梳理下,开发过程中遇到的问题,其中之一就是,通过MediaPlayer获取在线音频的时长,无法成功

分析

首先,看看mediaPlayer.getDuration()的源码,里面明确地说了,不支持在线内容,所以,根本原因就是它

/**
 * Gets the duration of the file.
 *
 * @return the duration in milliseconds, if no duration is available
 *         (for example, if streaming live content), -1 is returned.
 */
public native int getDuration();

如果使用其他音频播放的框架,感觉开发成本上划不来,而且时间上要求得很急。于是,我只能继续搜索,于是在github上找到了一个可用的获取在线音频的时长的框架,支持的格式和协议也很多,选它就可用了

https://github.com/wseemann/FFmpegMediaMetadataRetriever

使用起来也很方便

/**
 * 获取在线音频时间长度
 *
 * @param url
 * @return
 */
public static int getDurationInMilliseconds(String url) {
    FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
    mmr.setDataSource(url);
    int duration = Integer.parseInt(mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION));
    mmr.release();//释放资源
    return duration;
}

总结

MARK一下,留着后面做回顾
————————————————
版权声明:本文为CSDN博主「何浪」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/helang296479893/article/details/102498379

上一篇下一篇

猜你喜欢

热点阅读