在开发安卓音乐播放器时,歌词显示总会遇到中文显示乱码的问题;
发现是很多时候是由于,不同网站上下载的歌词可能编码格式不同,而我在解析歌词的时候统一都用的一种编码格式;
这样就很有可能造成编码格式不匹配,从而导致解析出来的String就是乱码;
为了避免这种问题,我们可以在读取歌词时,先用BufferedInputStream读取歌词前三个字节;
据此判断歌词的编码格式,然后在再用BufferedReader读取对应编码格式的歌词;
从而有效避免了歌词乱码的问题
代码如下:
public void init(File file) {
BufferedReader reader = null;
WeakReference<StringBuilder> weakSb;
WeakReference<BufferedReader> weakBr = null;
StringBuilder sb;
FileInputStream fis;
BufferedInputStream bis;
try {
if (null == file)
return;
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
bis.mark(4);
byte[] first3bytes = new byte[3];
bis.read(first3bytes);
bis.reset();
/**
* add by libeibei
* 动态识别歌词编码格式
* 防止出现乱码问题
* 2018-01-04
*/
if (first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB
&& first3bytes[2] == (byte) 0xBF) {// utf-8
Log.e("MusicPlayer","Lyric text type = utf-8");
reader = new BufferedReader(new InputStreamReader(bis, "utf-8"));
} else if (first3bytes[0] == (byte) 0xFF
&& first3bytes[1] == (byte) 0xFE) {
Log.e("MusicPlayer","Lyric text type = utf-unicode");
reader = new BufferedReader(
new InputStreamReader(bis, "unicode"));
} else if (first3bytes[0] == (byte) 0xFE
&& first3bytes[1] == (byte) 0xFF) {
Log.e("MusicPlayer","Lyric text type = utf-16be");
reader = new BufferedReader(new InputStreamReader(bis,
"utf-16be"));
} else if (first3bytes[0] == (byte) 0xFF
&& first3bytes[1] == (byte) 0xFF) {
Log.e("MusicPlayer","Lyric text type = utf-16le");
reader = new BufferedReader(new InputStreamReader(bis,
"utf-16le"));
} else {
Log.e("MusicPlayer","Lyric text type = GBK");
reader = new BufferedReader(new InputStreamReader(bis, "GBK"));
}
weakBr = new WeakReference<BufferedReader>(reader);
sb = new StringBuilder();
weakSb = new WeakReference<StringBuilder>(sb);
String temp = null;
WeakReference<String> weakTemp = new WeakReference<String>(temp);
while ((temp = weakBr.get().readLine()) != null) {
weakSb.get().append(temp).append("\n");
}
init(weakSb.get().toString());
sb = null;
weakSb = null;
System.gc();
} catch (Exception ex) {
Logger.getLogger(Lyric.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (null == reader)
return;
reader.close();
weakSb = null;
weakBr.get().close();
System.gc();
} catch (Exception ex) {
Logger.getLogger(Lyric.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}
网友评论