flash如果MP3的ID3標簽使用GB2312編碼,那么在FLASH腳本輸出時是亂碼的
代碼1
var s:Sound=new Sound(this);
s.loadSound("dxh.mp3",false);
s.onID3=function(){
trace(this.id3.songname);
}
輸出結果是:
¶¡Ïã»
dxh.mp3的ID3v1的標簽正確應該是songname="丁香花",看來FLASH在轉碼上出現了問題。我們來看看songname這個字符串中倒底是什么?
代碼2:
var s:Sound=new Sound(this);
s.loadSound("dxh.mp3",false);
s.onID3=function(){
var songname:String=this.id3.songname;
for(var i=0;i<songname.length;i++){
trace(songname.charCodeAt(i));
}
}
輸出結果是:
182
161
207
227
187
168
我們使用計算器轉換成16進制就是"B6 A1 CF E3 BB A8";
正好是"丁香花"的GB2312編碼,我們還是用FLASH來試試
System.useCodepage=true;
trace(unescape("%B6%A1%CF%E3%BB%A8"));
輸出結果是:
丁香花
那么為什么代碼1出現亂碼現象,是因為FLASH將GB2312當作了UTF-8來解釋,我們再來測試一下:
代碼3:
var s:Sound=new Sound(this);
s.loadSound("dxh.mp3",false);
s.onID3=function(){
var songname:String=this.id3.songname;
trace(escape(songname));
}
結果是:
%3F%3F%3F%3F%3F%A1%A7
問題的原因我們找到了,只要將GB2312轉換成UTF-8編碼就能顯示正常了,可是如果轉換呢,大家注意看代碼2,我再測試一下想法
代碼4:
System.useCodepage=true;
var gb:String=unescape("%B6%A1%CF%E3%BB%A8");
System.useCodepage=false;
trace(gb);
trace(escape(gb));
輸出結果:
丁香花
%E4%B8%81%E9%A6%99%E8%8A%B1
第二行就是“丁香花”的UTF-8編碼,說明已經轉換成功了,我們來具體實現這個過程
class lm.utils.LUTF {&n漀祰楲檜???水???o呀?bsp;
public function toUTF(source:String):String{
var target:String="";
for(var i=0;i<source.length;i++){
target+=this.codeTohex(source.charCodeAt(i));
}
System.useCodepage=true;
target=unescape(target);
System.useCodepage=false;
return target;
}
private function codeTohex(code:Number):String{
var low:Number=code%16;
var high:Number=(code-low)/16;
return "%"+hex(high)+hex(low);
}
private function hex(code:Number):String{
switch(code){
case 10:
return "A";
break;
case 11:
return "B";
break;
case 12:
return "C";
break;
case 13:
return "D";
break;
case 14:
return "E";
break;
case 15:
return "F";
break;
default:
return String(code);
break;
}
}
}
我們再來測試一下
import lm.utils.LUTF;
var u=new LUTF();
var s:Sound=new Sound(this);
s.loadSound("dxh.mp3",false);
s.onID3=function(){
var songname:String=_root.u.toUTF(this.id3.songname);
trace(songname);
}
輸出結果:
丁香花
到此為此我們已經解決了這個亂碼問題,使用這個技巧也可以解決其他的亂碼問題!