我正在制作一个应用程序,它将下载一个.zip文件,解压缩它,最后获取.srt文件(已压缩(并将其作为字幕文件放入 exoplayer 电影中。
- 我的问题
该文件里面有希腊字母,当我把它作为字幕文件时,我只看到损坏的字母
- 我试过什么
下面是解压缩文件的代码
fun writeZipAndUnZip(subtitlesLinks: ArrayList<String>, context: Context, body: ResponseBody?) {
if (body == null) { return }
val file = File(getSubsDirectory(), subtitlesLinks.first())
var inputStream: InputStream? = null
var outputStream: OutputStream? = null
try {
val fileReader = ByteArray(4096)
inputStream = body.byteStream()
outputStream = FileOutputStream(file)
while (true) {
var read = inputStream.read(fileReader)
if (read == -1) {
break
}
outputStream.write(fileReader, 0, read)
}
outputStream.flush()
unzip(context)
} catch (e: IOException) {
return
} finally {
inputStream?.close()
outputStream?.close()
}}
fun unzip(context: Context) {
val unzipPath = getSubsDirectory()
var count: Int
val buffer = ByteArray(4096)
val subFile = File(getSubsDirectory()).listFiles()?.first() ?: return
try {
val stream = FileInputStream(subFile.absolutePath)
ZipInputStream(stream).use { zis ->
var ze = ZipEntry("")
while (zis.nextEntry?.also { ze = it } != null) {
var fileName = ze.name
fileName = fileName.substring(fileName.indexOf("/") + 1)
val file = File(unzipPath, fileName)
val dir = if (ze.isDirectory) file else file.parentFile
if (!dir.isDirectory && !dir.mkdirs())
throw FileNotFoundException("Invalid path: " + dir.absolutePath)
if (ze.isDirectory) continue
val fileOutput = FileOutputStream(file)
try {
while (zis.read(buffer).also { count = it } != -1)
fileOutput.write(buffer, 0, count)
} catch (e: IOException) {
Timber.tag("ErrorZip").d(e.localizedMessage)
} finally {
val fileOutput = context.openFileOutput(fileName, Context.MODE_PRIVATE)
fileOutput.close()
}
}
}
} catch (e: IOException) {
Timber.tag("ErrorZip").d(e.localizedMessage)
}}
这是我在 exoplayer 中放入字幕的代码
val subtitleFormat = Format.createTextSampleFormat(null, MimeTypes.APPLICATION_SUBRIP, Format.NO_VALUE, "el")
val subtitleSource = SingleSampleMediaSource(File(Utils.getSubsDirectory()).listFiles()!![1].toUri(), dataSourceFactory, subtitleFormat, C.TIME_UNSET)
mediaSource = MergingMediaSource(buildMediaSource(videoUrl), subtitleSource)
我还尝试使用 Utf-8 编码重新保存字幕,但我得到了一些希腊语字符,使用此代码最缺少或不正确的字符
fun encode() {
val charset = "UTF8"
val subFile = File(getSubsDirectory()).listFiles()!![1] ?: return
val inputStream: InputStream = subFile.absoluteFile.inputStream()
val inputString = inputStream.bufferedReader().use { it.readText() }
val writer = OutputStreamWriter(FileOutputStream(File(getSubsDirectory(), "subs.srt")), charset)
writer.write(inputString)
writer.close()
}
您可能尝试读取的文件的编码与系统默认值不同(Android 使用utf-8
(。您需要以"正确"的编码格式读取文件(因为希腊语通常是Windows-1253
(,然后将其保存到utf-8
。