第一次寫部落格,邏輯有點亂,見諒~
Android從API16中更新對字幕追蹤的支援,具體是下面幾個方法。
Added in API level 16
public void addTimedTextSource (Context context, Uri uri, String mimeType) public void addTimedTextSource (String path, String mimeType) public void addTimedTextSource (FileDescriptor fd, long offset, long length, String mimeType) public void addTimedTextSource (FileDescriptor fd, String mimeType)
以第二方法為例,先看下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機制有關。
目前還沒有找到什麼辦法,解決這個問題....
嘗試過等視頻播放起來後在調用這個方法還是不行~
如果哪位已經解決了,請告訴我下,謝謝。
Added in
API level 16