我想用我的视频(.mp4)显示字幕(.srt) 我以数据的形式获取数据 JSON并解码它,E.g
视频网址:
http://www.example.com/wp-content/uploads/Amshrstry.S02E01.HDTV.x264.mp4
Subtile Url:http://www.example.com/wp-content/uploads/Amshrstry.S02E01.HDTV.x264.srt
我尝试了这个,它就像一个魅力,但我不能使用原始文件夹来读取字幕,我的所有数据fetchin来自我的网站(视频网址和字幕网址),所以我想从网址阅读字幕。
尝试过的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
MediaPlayer player = MediaPlayer.create(this, R.raw.video);
try {
player.addTimedTextSource(getSubtitleFile(R.raw.sub),
MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
int textTrackIndex = findTrackIndexFor(
TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT, player.getTrackInfo());
if (textTrackIndex >= 0) {
player.selectTrack(textTrackIndex);
} else {
Log.w(TAG, "Cannot find text track!");
}
player.setOnTimedTextListener(this);
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private String getSubtitleFile(int resId) {
String fileName = getResources().getResourceEntryName(resId);
File subtitleFile = getFileStreamPath(fileName);
if (subtitleFile.exists()) {
Log.d(TAG, "Subtitle already exists");
return subtitleFile.getAbsolutePath();
}
Log.d(TAG, "Subtitle does not exists, copy it from res/raw");
// Copy the file from the res/raw folder to your app folder on the
// device
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(resId);
outputStream = new FileOutputStream(subtitleFile, false);
copyFile(inputStream, outputStream);
return subtitleFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeStreams(inputStream, outputStream);
}
return "";
}
private void copyFile(InputStream inputStream, OutputStream outputStream)
throws IOException {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int length = -1;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
// A handy method I use to close all the streams
private void closeStreams(Closeable... closeables) {
if (closeables != null) {
for (Closeable stream : closeables) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我想使用Uri代替R.raw.sub
。我如何转换getSubtitleFile(R.raw.sub)
方法。
答案 0 :(得分:1)
用于从网络中读取文件用于例如URLConnection(您可以使用.getInputStream())。有关详细信息,请参阅http://developer.android.com/reference/java/net/URLConnection.html。
你可以打电话
File dest = new File("destination on SD card");
copyFile(urlConnection.getInputStream(), new FileOutputStream(dest));
以后在播放器中使用相同的文件:
player.addTimedTextSource(dest.getAbsolutePath(),
MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);