当前位置: 七九推 > 移动技术>移动开发>Android > Android SRT字幕文件基础操作讲解

Android SRT字幕文件基础操作讲解

2023年01月17日 Android 我要评论
简介需要在视频播放时,同步显示字幕,市面上主流的字幕文件一般为srt文件,一般流程为:从服务器请求一个url地址,此为zip字幕压缩文件,一般需要请求url,下载zip文件,解析zip文件得到字幕sr

简介

需要在视频播放时,同步显示字幕,市面上主流的字幕文件一般为srt文件,一般流程为:从服务器请求一个url地址,此为zip字幕压缩文件,一般需要请求url,下载zip文件,解析zip文件得到字幕srt文件,最后进行显示

下载

请求就不在此多言了,每个服务器请求体,返回题各异,没有参考价值。

下载zip文件我们需要在本地创建一个本地文件夹用来存储此文件。

创建文件夹

 public string createdirectory(string name) {
        file dir = new file(baseapplication.getcontext().getcachedir(), name);
        file file = baseapplication.getcontext().getexternalfilesdir(environment.directory_downloads);
        if (file != null) {
            dir = new file(file, name);
        }
        if (!dir.exists()) {
           dir.mkdirs();
        }
        return dir.tostring();
    }

文件下载

文件下载使用的开源框架filedownloader

 implementation 'com.liulishuo.filedownloader:library:1.7.7'//download

参数一:下载地址

参数二:文件存储地址

参数三:回调

从外部传入需要的下载参数,然后通过callback回调出去,进行页面更新操作

public void startdownloadfile(string url,string path,filedownloadercallback callback){
        filedownloader.getimpl().create(url).setpath(path,true).setlistener(new filedownloadlistener() {
            @override
            protected void pending(basedownloadtask task, int sofarbytes, int totalbytes) {
                callback.start();
            }
            @override
            protected void progress(basedownloadtask task, int sofarbytes, int totalbytes) {
            }
            @override
            protected void completed(basedownloadtask task) {
                callback.completed(task.getpath());
            }
            @override
            protected void paused(basedownloadtask task, int sofarbytes, int totalbytes) {
            }
            @override
            protected void error(basedownloadtask task, throwable e) {
                callback.failed();
            }
            @override
            protected void warn(basedownloadtask task) {
            }
        }).start();
    }

下载调用以及文件解析调用

此处建立文件下载文件夹以及解析完成的文件夹地址,然后通过调用上述filedownloader文件下载回调,然后在下载完成的回调中进行文件zip解析

 public void download(string url,string title,downloadresultcallback callback){
        string input = "inputdirectory";
        string output = "outputdirectory";
        string inpath = fileutils.getinstance().createdirectory(input);
        string outpath = fileutils.getinstance().createdirectory(output);
        string sub = fileutils.getinstance().createfile(inpath,"subtitlefile"+ file.separator);
        downloadutils.getinstance().startdownloadfile(url, sub, new downloadutils.filedownloadercallback() {
            @override
            public void start() {
                callback.downloadstart();
            }
            @override
            public void completed(string inputpath) {
                callback.downloadsuccess();
                string path = inputpath + "/" + title +".zip";
                try {
                    ziputils.unzipfolder(path,outpath);
                    callback.resolvesuccess();
                } catch (exception e) {
                    callback.resolvefailed(e.getmessage());
                    e.printstacktrace();
                }
            }
            @override
            public void failed() {
                callback.downloadfailed();
            }
        });
    }

解析

zip文件解析

此处被上述调用,用于zip文件解析

参数一:需要被解析的zip文件地址

参数二:输出文件夹地址

public class ziputils {
    public static void unzipfolder(string zipfilestring, string outpathstring)throws exception {
        java.util.zip.zipinputstream inzip = new java.util.zip.zipinputstream(new java.io.fileinputstream(zipfilestring));
        java.util.zip.zipentry zipentry;
        string szname = "";
        while ((zipentry = inzip.getnextentry()) != null) {
            szname = zipentry.getname();
            if (zipentry.isdirectory()) {
                // get the folder name of the widget
                szname = szname.substring(0, szname.length() - 1);
                java.io.file folder = new java.io.file(outpathstring + java.io.file.separator + szname);
                folder.mkdirs();
            } else {
                java.io.file file = new java.io.file(outpathstring + java.io.file.separator + szname);
                file.createnewfile();
                // get the output stream of the file
                java.io.fileoutputstream out = new java.io.fileoutputstream(file);
                int len;
                byte[] buffer = new byte[1024];
                // read (len) bytes into buffer
                while ((len = inzip.read(buffer)) != -1) {
                    // write (len) byte from buffer at the position 0
                    out.write(buffer, 0, len);
                    out.flush();
                }
                out.close();
            }
        }//end of while
        inzip.close();
    }//end o
}

外部引用

参数一:下载url地址

参数二:存储文件夹名称

参数三:callback

上述zip文件下载以及zip文件解析为一个封装类,此处为在外部传入参数,通过回调进行页面更新,然后在resolvesuccess()方法中进行异步操作(此方法代表zip文件被下载成功并且已被成功解析)

private void download(){
        if (titlebeanlist == null || titlebeanlist.size() == 0)return;
        if (cursubtitlepos == 0)return;
        downloadutils.getinstance().download(titlebeanlist.get(cursubtitlepos).getsub(), titlebeanlist.get(cursubtitlepos).gett_name(), new downloadutils.downloadresultcallback() {
            @override
            public void downloadstart() {
                log.d(tag,"download start");
            }
            @override
            public void downloadsuccess() {
                log.d(tag,"download success");
            }
            @override
            public void downloadfailed() {
                log.d(tag,"download fail");
            }
            @override
            public void resolvesuccess() {
                log.d(tag,"resolve success");
                handler.sendemptymessage(6);
            }
            @override
            public void resolvefailed(string failmsg) {
                log.d(tag,"resolve error:"+failmsg);
            }
        });
    }

转换

转换srt字幕文件

通过将本地的srt字幕文件转为相对应集合实体数据,具体实体类型根据srt文件内容而定

 public static list<srtentity> getsrtinfolist(string srtpath){
        list<srtentity> srtlist = new arraylist<>();
        try {
            inputstreamreader read = new inputstreamreader(new fileinputstream(srtpath), "utf-8");
            bufferedreader bufferedreader = new bufferedreader(read);
            string textline;
            cursorstatus cursorstatus = cursorstatus.none;
            srtentity entity = null;
            while ((textline = bufferedreader.readline()) != null){
                textline = textline.trim();
                if (cursorstatus == cursorstatus.none) {
                    if (textline.isempty()) {
                        continue;
                    }
                    if (!isnumeric(textline)){
                        continue;
                    }
                    // new cue
                    entity = new srtentity();
                    // first textline is the cue number
                    try {
                        entity.setnumber(integer.parseint(textline));
                    } catch (numberformatexception e) {
                    }
                    cursorstatus = cursorstatus.cue_id;
                    continue;
                }
                // second textline defines the start and end time codes
                // 00:01:21,456 --> 00:01:23,417
                if (cursorstatus == cursorstatus.cue_id) {
                    if (!textline.substring(13, 16).equals("-->")) {
                        throw new exception(string.format(
                                "timecode textline is badly formated: %s", textline));
                    }
                    entity.setbg(parsetimecode(textline.substring(0, 12)));
                    entity.seted(parsetimecode(textline.substring(17)));
                    cursorstatus = cursorstatus.cue_timecode;
                    continue;
                }
                // following lines are the cue lines
                if (!textline.isempty() && (
                        cursorstatus == cursorstatus.cue_timecode ||
                                cursorstatus ==  cursorstatus.cue_text)) {
                    entity.addline(textline);
                    cursorstatus = cursorstatus.cue_text;
                    continue;
                }
                if (cursorstatus == cursorstatus.cue_timecode && textline.isempty()) {
                    entity.addline(textline);
                    cursorstatus = cursorstatus.cue_text;
                    continue;
                }
                if (cursorstatus == cursorstatus.cue_text && textline.isempty()) {
                    // end of cue
                    srtlist.add(entity);
                    entity = null;
                    cursorstatus = cursorstatus.none;
                    continue;
                }
            }
        } catch (unsupportedencodingexception e) {
            e.printstacktrace();
            log.e(tag, e.getmessage());
        } catch (filenotfoundexception e) {
            e.printstacktrace();
            log.e(tag, e.getmessage());
        } catch (ioexception e) {
            e.printstacktrace();
            log.e(tag, e.getmessage());
        } catch (exception e) {
            e.printstacktrace();
            log.e(tag, e.getmessage());
        }
        return srtlist;
    }

获取srt文件list实体数据

通过以上步骤之后,即可将srt文件转为相对应的list实体数据,最后与视频声音进行同步即可达到字幕与声音同步的效果

        string outpath = fileutils.getinstance().createdirectory("outputdirectory");
        string path = outpath +"/" +titlebeanlist.get(cursubtitlepos).gett_name();
        srtentitylist.addall(srtparser.getsrtinfolist(path));

显示

字幕显示

然后通过获取字幕文件的片段的开始时间与结束时间,若当前视频的播放进度在此范围之内,即显示字幕,否则继续寻找;

private void showsubtitle(){
        if (srtentitylist == null || srtentitylist.size() == 0)return;
        for (int i = cursubtitlenum; i < srtentitylist.size(); i++) {
            long start = srtentitylist.get(i).getbg().gettime()+subtitlespeed;
            long end = srtentitylist.get(i).geted().gettime()+subtitlespeed;
            if (curprogress >= start && curprogress <= end){
                /**
                 * 字幕与进度相匹配*/
                binding.videoplay.setsubtitle(srtentitylist.get(i).content.gettext());
                cursubtitlenum = i;
                break;
            }
        }
    }

若用户往前拖动视频进度条,则将字幕文件片段下标置为0,从头开始匹配

 if (currentposition - curprogress < 0){
                            //seek --
                            cursubtitlenum = 0;
                        }

到此这篇关于android srt字幕文件基础操作讲解的文章就介绍到这了,更多相关android srt字幕文件内容请搜索七九推以前的文章或继续浏览下面的相关文章希望大家以后多多支持七九推!

(0)
打赏 微信扫一扫 微信扫一扫

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2023  七九推 保留所有权利. 粤ICP备17035492号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com