第一次写博客,逻辑有点乱,见谅~
Android从API16中更新对字幕追踪的支持,具体是下面几个方法。
Added in API level 16
以第二方法为例,先看下API注释:
Added in API level 16
Adds an external timed text source file. Currently supported format is SubRip with the file extension .srt, case insensitive. Note that a single external timed text source may contain multiple tracks in it. One can find the total number of available tracks using getTrackInfo()
to see what additional tracks become available after this method call.
大致意思就是,MediaPlayer支持外置文件显示字幕,但是现在只支持.SRT格式。这个文件可能有多个追踪器在追踪它,可以通过调用getTrackInfo()方法来获得所有的追踪器。
TrackInfo 共有四种类型,未知,视频,音频,字幕。
Added in API level 16
public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
在调用的时候,经常遇到这个错误:
03-29 14:42:38.675: W/System.err(21382): java.lang.RuntimeException: failure code: -38
03-29 14:42:38.675: W/System.err(21382): at android.media.MediaPlayer.invoke(MediaPlayer.java:644)
03-29 14:42:38.675: W/System.err(21382): at android.media.MediaPlayer.addTimedTextSource(MediaPlayer.java:1814)
03-29 14:42:38.675: W/System.err(21382): at android.media.MediaPlayer.addTimedTextSource(MediaPlayer.java:1778)
03-29 14:42:38.675: W/System.err(21382): at android.media.MediaPlayer.addTimedTextSource(MediaPlayer.java:1710)
03-29 14:42:38.675: W/System.err(21382): at com.demo.devin.fragment.QosDemoFragment$VideoHolder.onPrepared(QosDemoFragment.java:224)
API中告诉我们会抛这些Exception:
Added in API level 16
Throws: IOException - if the file cannot be accessed or is corrupted. IllegalArgumentException - if the mimeType is not supported. IllegalStateException - if called in an invalid state.
经过试验,在OnPrepared的时候调用没有问题!
但是只是调用这个方法是无法工作的,还需要注册响应的listener和调用selectTrack方法。
具体代码如下:(在OnPrepared回调中)
try { mMediaPlayer.addTimedTextSource(srtPath, MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP); TrackInfo[] trackInfos = mMediaPlayer.getTrackInfo(); if (trackInfos != null && trackInfos.length > 0) { for (int i = 0; i < trackInfos.length; i++) { final TrackInfo info = trackInfos[i]; Log.w(TAG, "TrackInfo: " + info.getTrackType() + " " + info.getLanguage()); if (info.getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_AUDIO) { // mMediaPlayer.selectTrack(i); } else if (info.getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT) { mMediaPlayer.selectTrack(i); } } } } catch (Exception e) { e.printStackTrace(); }
之后再注册的OnTimedTextListener中,会触发该回调,再配合TextView就是实现字幕了,Android已经做好了同步功能!
以上是我在播放MP4流时,可以正常工作!但是在播放M3U8流时,不能工作还是抛了RunTimeException这个异常,可能和MediaPlayer的OnPrepared机制有关。
目前还没有找到什么办法,解决这个问题....
尝试过等视频播放起来后在调用这个方法还是不行~
如果哪位已经解决了,请告诉我下,谢谢。