• ActionScript


    Action Script:

    Sprite [sprait] 精灵;雪碧;子画面(画布)

    调试函数trace(string)

    一般事件:
    import flash.events.Event;
    addEventListener(Event.ENTER_FRAME,myFunction);


    鼠标事件:
    import flash.events.MouseEvent;
    public function ActionScriptDemo()
    {
     //在构造函数中定义画布
     _sprite = new Sprite();
     addChild(_sprite);  //增加画布
     _sprite.graphics.beginFill(0xeeffcc);  //画布的颜色
     _sprite.graphics.drawRect(0,0,400,400);  //画布的形状
     _sprite.graphics.endFill();  //完成绘画
     //定义鼠标事件
     _sprite.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
     _sprite.addEventListener(MouseEvent.MOUSE_UP,onMouseUp);
    }
    private function onMouseDown(event:MouseEvent):void
    {
     _sprite.graphics.lineStyle(1,0,1);  //定义线条属性
     _sprite.graphics.moveTo(mouseX,mouseY);  //更新起始點
     _sprite.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);  //MouseDown时添加响应事件onMouseMove
    }
    private function onMouseUp(event:MouseEvent):void
    {
     _sprite.removeEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
    }
    private function onMouseMove(event:MouseEvent):void
    {
     _sprite.graphics.lineTo(mouseX,mouseY);  //画线
    }


    键盘事件:
    private function onKeyDown(event:KeyboardEvent):void
    {
     trace("key down:" + event.charCode);
    }

    switch,表达式包括在小括号里;default不用加break;case不加break时可以贯穿。

    Timer类是ActionScript3.0新增的类,建议将其用来替代以前的setInterval()和setTimeout()函数。

    import flash.display.Sprite;
    import flash.events.TimerEvent;
    import flash.utils.Timer;

    public class ActionScriptDemo extends Sprite
    {
     private var _PreviousTime:Number=0;
     public function ActionScriptDemo()
     {
      var tTimer:Timer = new Timer(500,10);  //间隔0.5秒,重复10次
      tTimer.addEventListener(TimerEvent.TIMER,onTimer);
      tTimer.start();
     }
     private function onTimer(event:TimerEvent):void
     {
      trace(flash.utils.getTimer() - _PreviousTime);  //当前时间-原来时间
      _PreviousTime = flash.utils.getTimer();
     }
    }

    //timer part2
    private var _square:Sprite;
    private var _circle:Sprite;
    public function ActionScriptDemo()
    {
     stage.scaleMode = flash.display.StageScaleMode.NO_SCALE;  //没有比例(原始大小)
     stage.align = flash.display.StageAlign.TOP_LEFT;  //窗口缩放时内容仍左上对齐
     
     _square = new Sprite();
     _square.graphics.beginFill(0xffeecc);
     _square.graphics.drawRect(0,0,100,100);
     _square.graphics.endFill();
     addChild(_square); 
     _square.x = 100;
     _square.y = 50;
     
     _circle = new Sprite();
     _circle.graphics.beginFill(0xcceeff);
     _circle.graphics.drawCircle(50,50,50);
     _circle.graphics.endFill();
     addChild(_circle);
     _circle.x=100;
     _circle.y=200;
     
     var squareTimer:Timer = new Timer(50);
     squareTimer.addEventListener(TimerEvent.TIMER,onSquareTimer);
     squareTimer.start();
     
     var circleTimer:Timer = new Timer(100);
     circleTimer.addEventListener(TimerEvent.TIMER,onCircleTimer);
     circleTimer.start();
    }
    private function onSquareTimer(event:TimerEvent):void
    {
     _square.x ++;
    }
    private function onCircleTimer(event:TimerEvent):void
    {
     _circle.x ++;
    }

    有参方法:
    private function average(a:Number,b:Number,c:Number):Number{
     return (a+b+c)/3;
    }

    处理错误:
    private function test():void
    {
     try
     {
      throw new Error("my error");
     }
     catch(errObject:Error)
     {
      trace("The Error Message is: " + errObject.message);
      return;  //有异常则返回
     }
     finally
     {
      trace("whatever it returns or not");
     }
     trace("can't arrive here");
    }

    检测操作系统:
    var os:String = flash.system.Capabilities.os.substr(0,3);
    if(os=="Win") { /*windows专用代码*/ }
    else if(os=="Mac") { /*Mac专用代码*/ }
    else { /*一定是Unix或Linux*/ }

    检查播放器类型:
    var type:String = flash.system.Capabilities.playerType;
    if(type=="Plugin") { /*Mozilla浏览器*/ }
    else if(type=="ActiveX") { /*IE浏览器*/ }
    else { /*非浏览器*/ }

    检查系统语言:
    var lang:String = flash.system.Capabilities.language.substr(0,2);
    var ary:Array = ["en","es","fr"];
    var useLang:String = "en";
    for(var i:int=0;i<ary.length;i++)
    {
     if(ary[i]==lang)
     {
      useLang = lang; 
      break;
     }
    }
    var movieURL:String = "myMovie_" + useLang + ".swf";  //加载相应的影片

    禁用常用菜单:
    stage.showDefaultContextMenu = false;

    检查音频:
    if(flash.system.Capabilities.hasAudio)  //有声频时
    if(flash.system.Capabilities.hasMP3)  //可以播放MP3时

    产生随机数
    Math.random()产生一个介于0和0.999 999 999之间的随机浮点数

    产生一个指定范围的随机数并且具有指定的精度
    NumberUtilities.random(),此方法最多可以接受三个参数,分别是最小值,最大值,取整数时所用的间距。

    定义数组:
    var ary:Array = new Array("a","b","c");
    var ary2:Array = ["a","b","c"];
    var data:Array = ["a",2,true,new Object()];

    数组插入数据:
    var ary:Array = new Array("a","b","c");
    ary[5] = "f";  //ary变成:["a","b","c",undefined,undefined,"f"]
    for(var i:int =0;i<ary.length;i++) trace(ary[i]);

    搜索数组里某个元素的下标,可以用for历遍,也可以用ArrayUtilities里的静态方法。略。

    去掉数组的某个元素,可以用splice ([splais],接合)
    var ary:Array = new Array("a","b","c");
    ary.splice(2,1);  //从下标2处移除一个元素,ary变成:["a","b"]
    for(var i:int =0;i<ary.length;i++) trace(ary[i]);

    用splice移除数组元素时,必须相应地更改索引变量的值:
    var ary:Array = new Array("a","b","c",undefined,undefined,"f");
    for(var i:int =0;i<ary.length;i++) 

     if(ary[i]==undefined) ary.splice(i,1);
    }
    for(var j:int =0;j<ary.length;j++) 
    {
     trace(ary[j]);
    }
    //以上程序并没有移除所有的undefined元素,ary变成了["a","b","c",undefined,"f"]。
    //因为移除ary[3]时,后面的元素下标会向前移(C#也一样),ary[4]变成了f,如果要实现目的,应该这样:
    if(ary[i]==undefined)
    {
     ary.splice(i,1);
     i--;
    }

    数组连接成字符串:
    var ary:Array = ["a","b","c"];
    trace(ary.join("|"));  //a|b|c,没有参数时默认为,

    数组排序:
    var ary:Array = ["a","c","b"];
    ary.sort();  //按字母排,ary.sort(Array.DESCENDING)降序
    trace(ary);
    默认排序时区分大小写,大写开头的元素会放在前面。如果要不区分大小写,可以用Array.CASEINSENSITIVE。
    Array.NUMERIC是以数字值大小为准,而不是编码顺序。可以用来得到最大值和最小值。
    Array.UNIQUESORT,只在数组的每个元素都是独一无二时才排序。
    Array.RETURNINDEXEDARRAY,得到数组元素的排序顺序,但又不改变原有的数组
    数组倒序:ary.reverse();  如ary为["ab","cd","ef"]时,则输出ef,cd,ab,注意只是元素整体倒序,并不是每个字符
    sortOn(),用来根据对象的某个属性排序。如sortOn("NewsTitle");

    /*第六章*/
    //创建圆形
    public function CreateCircle(color:uint,radius:Number,x:Number,y:Number):Shape
    {
     var shape:Shape = new Shape();
     shape.graphics.beginFill(color);
     shape.graphics.drawCircle(x,y,radius);
     shape.graphics.endFill();
     return shape;
    }
    Sprite是去掉了时间轴的MovieClip(即阉割版MovieClip)。
    Sprite不同于Shape,区别就在于Sprite是容器,而Shape不是。从代码角度说就是,Sprite可以addChild(),但Shape不可以。
    Sprite支持鼠标单击事件,而Shape不支持。
     
    移除图形:
    private var text:TextField;
    public function ActionScriptDemo()
    {
     text = new TextField();
     text.text = "ookk";
     addChild(text);  //因为这里是加到sprite上(继承了sprite)
     
     stage.addEventListener(MouseEvent.CLICK,removeText);
    }
    public function removeText(event:MouseEvent):void
    {
     removeChild(text);  //所以这里不能加stage
    }

    addChildAt和removeChildAt汲及到index,略

    setChildIndex(a,getChildIndex(b)); a和b的高低位置会调转。

    导入图片:
    把测试图片放到html-template(swf所在的目录)下。
    stage.scaleMode = flash.display.StageScaleMode.NO_SCALE;  //没有比例(原始大小)
    stage.align = flash.display.StageAlign.TOP_LEFT;  //窗口缩放时内容仍左上对齐
    var loader:Loader = new Loader();
    loader.load(new URLRequest("test.gif"));
    addChild(loader);
    //加上进度显示:
    public function ActionScriptDemo()
    {
     stage.scaleMode = flash.display.StageScaleMode.NO_SCALE;  //没有比例(原始大小)
     stage.align = flash.display.StageAlign.TOP_LEFT;  //窗口缩放时内容仍左上对齐
     
     var loader:Loader = new Loader();
     loader.load(new URLRequest("test.gif"));
     addChild(loader);
     loader.contentLoaderInfo.addEventListener(Event.OPEN,handleOpen);
     loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,handleProgress);
     loader.contentLoaderInfo.addEventListener(Event.COMPLETE,handleComplete);
    }

    private function handleOpen(event:Event):void
    {
     trace("open");
    }
    private function handleProgress(event:ProgressEvent):void
    {
     var percent:Number = event.bytesLoaded/event.bytesTotal * 100;
     trace("progress,percent = " + Math.ceil(percent).toString()+"%");  //取整显示
    }
    private function handleComplete(event:Event):void
    {
     trace("complete");
    }

    //鼠标点击事件
    private function onClick(event:MouseEvent):void
    {
     trace("click" + event.localX + event.localY);  //可以用坐标判断做某事
    }

    //画直线
    var s:Sprite = new Sprite();
    s.graphics.lineStyle(1);  //定义画线属性
    s.graphics.moveTo(0,0);  //初始点
    s.graphics.lineTo(100,100);  //终点
    addChild(s);
    //曲线:Graphics.curveTo(),矩形:Graphics.drawRect(),圆形:Graphics.drawCircle(),
    //椭圆:Pen.drawEllipse(),弧线:pen.drawArc(),三角形:Pen.drawTriangle(),正多边形:Pen.drawRegularPolygon(),星形:Pen.drawStar()。


    //文本框:
    var txt:TextField = new TextField();
    txt.border=true;  //边框
    txt.borderColor = 0xffccee;  //边框色
    addChild(txt);  //加入舞台
    txt.background = true;  //为了设置背景色,仍然起作用
    txt.backgroundColor = 0xe3e3e3;  //默认为白色
    txt.type = TextFieldType.INPUT;  //可输入
    txt.displayAsPassword = true;  //密码形式输入
    //txt.selectable = false;  //可选择,默认为true,false时不可输入

    txt.restrict = "abc";  //过滤字符,只能输入a或b或c
    txt.restrict = "0-9";  //只能输入数字
    txt.restrict = "a-zA-Z";  //只能输入字母
    txt.restrict = "a-zA-Z ";  //只能输入字母和空格
    txt.restrict = "^abc";  //除了小写字母a到c,注意输入abc时会自动转成大写
    txt.restrict = "^a-z";  //除了小写字母
    txt.restrict = "0-9^5";  //0到9除了5

    txt.maxChars = 6;  //最长6个字符
    txt.text = "ookkhahaxixi";  //显示文本,不受maxChars影响
    txt.appendText("ookk");  //追加文本
    txt.htmlText = "<u>this is underlined text</u>";  //会解释为html(text属性则不会),会覆盖掉text属性
    txt.condenseWhite = true;  //缩减空白,只留一个空白(htmltext时有效)
    txt.htmlText = "hello      world";  //显示 hello world
    txt.autoSize = "left";  //文本向左对齐(自动调整文本框大小),还支持right,center,none

    txt.scrollV = 1;  //滚动至顶端
    txt.scrollV += 1;  //滚动至下一行
    txt.scrollV = 6;  //滚动至第六行
    txt.scrollV = txt.bottomScrollV;  //滚动至下一页,保留上一页最后一项
    txt.scrollV = txt.bottomScrollV + 1;  //滚动至下一页,不存在上一页信息
    txt.scrollH = 0;  //滚动至最左
    txt.scrollH += 1;  //向右滚动1像素
    txt.scrollH = txt.maxScrollH;  //滚动至最右
    txt.mouseWheelEnabled = true;  //鼠标轮滚动
    //可以响应滚动事件 txt.addEventListener(Event.SCROLL,myFun);

    //样式
    var formatter:TextFormat = new TextFormat();
    formatter.bold = true;  //字体加粗
    formatter.color = 0xffeecc;  //颜色
    formatter.blockIndent = 2;  //每段首行缩进(略)
    txt.setTextFormat(formatter);  //应用样式
    txt.text = "rewrite";  //重新赋值后格式自动取消
    txt.setTextFormat(formatter);  //要重新赋格式
    //txt.defaultTextFormat = formatter;  可以设置默认格式,这样格式就不会丢掉了

    //加载css样式
    public function ActionScriptDemo()
    {
     var loader:URLLoader = new URLLoader();
     var request:URLRequest = new URLRequest("css.css");  //定义下载信息
     loader.load(request);  //加载下载信息
     
     loader.addEventListener(Event.COMPLETE,onLoadCss);  //定义完成事件
    }  
    private function onLoadCss(event:Event):void
    {
     var css:StyleSheet = new StyleSheet();
     css.parseCSS(URLLoader(event.target).data);  //通过URLLoader的事件目标取得css的data
     
     var field:TextField = new TextField();
     field.styleSheet = css;  //应用样式
     
     field.autoSize = "left";
     field.wordWrap = true;
     field.width = 200;
     field.htmlText = "<p>ookk</p>";
     
     addChild(field);
    }

    //选择字符
    var txt:TextField = new TextField();
    txt.text = "abc";
    stage.focus = txt;  //为了选择字符
    txt.setSelection(0,2);
    addChild(txt);

    //文本响应事件:
    FocusEvent.FOCUS_IN(当焦点移进文本时),FocusEvent.FOCUS_OUT(焦点移出),TextEvent.TEXT_INPUT(内容改变)

    //超链接事件/点击事件
    public function ActionScriptDemo()
    {
     var txt:TextField = new TextField();
    //txt.htmlText = "<a href='http://www.baidu.com'>abc</a>";  //正常的超链接事件
     txt.htmlText = "<a href='event:http://www.ookk.com'>abc</a>";  //利用event实现自义定事件,href的值不必为有效的URL
     txt.addEventListener(TextEvent.LINK,test);
     addChild(txt);   
    }  
    private function test(event:TextEvent):void{
     trace("click me");
    }

    /*第十章 滤镜和转换 略*/

    //移动对象
    addEventListener(Event.ENTER_FRAME,myFun);  //定义ENTER_FRAME事件
    ...
    private function myFun(event:Event):void{ _sprite.x += 3; }

    var _timer:Timer = new Timer(1000);  //定义Timer对象
    _timer.addEventListener("timer",onTimer);
    _timer.start();
    ...
    private function onTimer(event:Event):void{ _sprite.x += 3; }

    //角度计算:一个圆是360度,2PI弧度。
    想以135度及每帧4像素的速率移动:(速度=有方向的速率)
    ==>要计算出X和Y的速度
    vx = Math.cos(angle) * speed; //x方向的速率=Math.cos(角度)*速率
    vy = Math.sin(angle) * speed;
    ==>onTimer(event:TimerEvent)函数
    _sprite.x -= vx;  //cos(钝角)为负值
    _sprite.y += vy;
    //代码
    private var _sprite:Sprite;
    private var _angle:Number = 135;
    private var _speed:Number = 4;
    private var _timer:Timer;
    public function ActionScriptDemo()
    {
     _sprite = new Sprite();
     _sprite = ExtendPackage.CreateShape.CreateCircle(0x0000ff,25,0,0);  //造圆
     addChild(_sprite);
     _timer = new Timer(30);
     _timer.addEventListener("timer",onTimer);
     _timer.start();
     
    }  
    public function onTimer(event:TimerEvent):void{
     var radians:Number = _angle * Math.PI / 180;
     var vx:Number = Math.cos(radians) * _speed;
     var vy:Number = Math.sin(radians) * _speed;
     _sprite.x -= vx;
     _sprite.y += vy;
    }

    //缓慢移动:每次按照剩余距离的N分之1来移动
    private var _sprite:Sprite;
    private var _targetX:Number = 400;
    private var _targetY:Number = 200;
    private var _timer:Timer;
    private var _easingSpeed:Number = 0.1;  //移动1/10
    public function ActionScriptDemo()
    {
     _sprite = new Sprite();
     _sprite = ExtendPackage.CreateShape.CreateCircle(0x0000ff,25,0,0);
     addChild(_sprite);
     _timer = new Timer(30);
     _timer.addEventListener("timer",onTimer);
     _timer.start();
     
    }  
    public function onTimer(event:TimerEvent):void{
     var vx:Number = (_targetX - _sprite.x) * _easingSpeed;
     var vy:Number = (_targetY - _sprite.y) * _easingSpeed;
     _sprite.x += vx;
     _sprite.y += vy;
    }
    //存在问题,即使对象已经非常接近目标,计时器还是会继续跑下去。解决思路:如果距离少于某特定值就关掉计时器
    public function onTimer(event:TimerEvent):void
    {
     var dx:Number = _targetX - _sprite.x;
     var dy:Number = _targetY - _sprite.y;
     var dist:Number = Math.sqrt(dx*dx + dy*dy); 
     if(dist<1)  //距离小于1则停止
     {
      _sprite.x = _targetX;
      _sprite.y = _targetY;
      _timer.stop();
     }
     else
     {
      var vx:Number = dx * _easingSpeed;
      var vy:Number = dy * _easingSpeed;
      _sprite.x += vx;
      _sprite.y += vy;
     }
    }

    //弹性:
    private var _sprite:Sprite;
    private var _vx:Number = 20;
    private var _vy:Number = 0;
    private var _k:Number = 0.1;
    private var _damp:Number = 0.94;
    private var _targetX:Number = 200;
    private var _targetY:Number = 200;

    public function ActionScriptDemo()
    {
     _sprite = new Sprite();
     _sprite = ExtendPackage.CreateShape.CreateCircle(0x0000ff,25,0,0);
     addChild(_sprite);
     addEventListener(Event.ENTER_FRAME,onEnterFrame);   
    }  
    public function onEnterFrame(event:Event):void{
     var ax:Number = (_targetX - _sprite.x) * _k;
     var ay:Number = (_targetX - _sprite.x) * _k;
     _vx += ax;
     _vy -= ay;
     _sprite.x += _vx;
     _sprite.y += _vy;
     _vx *= _damp;
     _vy *= _damp;
    }

    //字符串
    AS(ActionScript)没有区分单一字符和字符串。字符和字符串都属于String类型。
    如果要输出多个数字连接起来的字符串(不是数字相加),可以在开始处接一个空字符串。如:
    var first:int = 1;
    var second:int = 2;
    var result:String = "" + first + second;
    如果把空字符串放在最后,则会先把两数相加,再转成字符串输出(和C#一样)
    字符串中有双引号时,可以用转义字符串把双引号转义再输出
    查找子字符串:indexOf(),lastIndexOf()
    提取子字符串:substring(),substr(),slice()  //slice可接受负数
    分解字符串:split(),AS里用单/双引号都行,C#里用单引号。
    移除和替换字符串:replace(),或split()和join()结合使用
    取出一个字符:String.charAt()
    转换大小写:toUpperCase(),toLowerCase()


    //声音编程
    private var _sound:Sound;
    public function ActionScriptDemo()
    {
     _sound = new Sound();
     _sound.load(new URLRequest("test.mp3"));
     //以上两句等价于:_sound = new Sound(new URLRequest("test.mp3"));
     //为声音加上缓冲:_sound = new Sound(new URLRequest("test.mp3"),new SoundLoaderContext(5000));  //建立5秒缓冲区
     _sound.play();
     //_sound.play(5500);  //声音从5秒处开始播放
     //推而广之,一段声音可以设置几个播放点,当用户点击某个按钮时,将播放点传进去
     //_sound.play(0,3);  //从开始处播放,循环3次
     //var _channel:SoundChannel = _sound.play();  //可以用来监听声音是否播放完成
     //_channel.addEventListener(Event.SOUND_COMPLETE,onComplete);  //在onComplete播放下一首

    //取得声音大小/百分比
    private var _sound:Sound;
    public function ActionScriptDemo()
    {
     addEventListener(Event.ENTER_FRAME,onEnterFrame);
     _sound = new Sound();
     _sound.load(new URLRequest("http://www.xxx.com/somestringfrombaidump3.mp3"));
     _sound.play();   
    }  
    public function onEnterFrame(event:Event):void{
     var barWidth:Number = 200;
     var barHeight:Number = 5;
     var loaded:int = _sound.bytesLoaded;
     var total:int = _sound.bytesTotal;
     if(total>0)
     {
      graphics.clear();
      graphics.beginFill(0xffccee);
      graphics.drawRect(10,10,barWidth,barHeight);
      graphics.endFill();
      var percent:Number = loaded/total;
      graphics.beginFill(0xcccccc);
      graphics.drawRect(10,10,barWidth*percent,barHeight);  //第二次画图;起始坐标一样
      graphics.endFill();
     }
    }

    //取得歌曲信息
    public function ActionScriptDemo()
    {
     _sound = new Sound();
     _sound.load(new URLRequest("test.mp3"));
     _sound.addEventListener(Event.ID3,onID3);
     _sound.play();   
    }  
    public function onID3(event:Event):void{
     var id3Display:TextField = new TextField();
     addChild(id3Display);
     id3Display.x = 10;
     id3Display.y = 20;
     id3Display.width = 200;
     id3Display.height = 200;
     id3Display.background = true;
     id3Display.multiline = true;
     id3Display.wordWrap = true;
     
     id3Display.appendText("begin\n");
     id3Display.appendText(_sound.id3.songName + "\n");
     id3Display.appendText(_sound.id3.artist + "\n");
     id3Display.appendText(_sound.id3.album + "\n");
     id3Display.appendText(_sound.id3.year + "\n");
     id3Display.appendText("end\n");
    }


    //跟踪声音播放速度
    private var _sound:Sound;
    private var _channel:SoundChannel;
    public function ActionScriptDemo()
    {
     addEventListener(Event.ENTER_FRAME,onEnterFrame);
     _sound = new Sound();
     _sound.load(new URLRequest("http://www.xxx.com/somestringfrombaidump3.mp3"));
        _channel = _sound.play();   
    }  

    public function onEnterFrame(event:Event):void{
     var barWidth:Number = 200;
     var barHeight:Number = 5;
     var loaded:int = _sound.bytesLoaded;
     var total:int = _sound.bytesTotal;
     var length:int = _sound.length;
     var position:int = _channel.position;  //播放位置
     
     graphics.clear();
     graphics.beginFill(0xeeccff);
     graphics.drawRect(10,10,barWidth,barHeight);
     graphics.endFill();
     
     if(total>0)
     {
      var percentBuffered:Number = loaded/total;
      graphics.beginFill(0xcccccc);
      graphics.drawRect(10,10,barWidth*percentBuffered,barHeight);
      graphics.endFill();
      
      length /= percentBuffered;
      var percentPlayed:Number = position / length;  //播放位置/总长度=播放百分
      
      graphics.beginFill(0x666666);
      graphics.drawRect(10,10,barWidth*percentPlayed,barHeight);
      graphics.endFill();
     }
    }  

    //暂停和重启声音
    private var _sound:Sound;
    private var _channel:SoundChannel;
    private var _playPauseButton:Sprite;
    private var _playing:Boolean = false;
    private var _position:int;
    public function ActionScriptDemo()
    {
     _sound = new Sound();
     _sound.load(new URLRequest("http://api.ning.com/files/EmiY8MvYE7-InlLGvoTGHkdYGmvaQIcZvWK3mcHnnfQJ97xKLx3aBL9dYzw8UmFvYrsYHsyGEFIWn3i2bmgYZ47s-38rUNZi/file.mp3?stdfrom=3"));
        _channel = _sound.play(); 
     _playing = true;
     
     //画停止按钮
     _playPauseButton = new Sprite();
     addChild(_playPauseButton);
     _playPauseButton.x = 10;
     _playPauseButton.y = 20;
     _playPauseButton.graphics.beginFill(0xcccccc);
     _playPauseButton.graphics.drawRect(0,0,20,20);
     //增加事件
     _playPauseButton.addEventListener(MouseEvent.MOUSE_UP,onPlayPause);
    }  

    public function onPlayPause(event:MouseEvent):void{
     if(_playing){  //如果是正在揪放时点击
      _position = _channel.position;  //记录位置
      _channel.stop();
     }
     else{  //播放
      _channel = _sound.play(_position);
     }
     _playing = !_playing;
    }  


    //声音音量
    _channel = _sound.play(); 
    var transform:SoundTransform = new SoundTransform();
    transform.volume = 0.3;  //30%的声音
    //以上两句等价于:var transform:SoundTransform = new SoundTransform(0.3);
    //还可以加声道参数,其值从-1.0(全左声道)到1.0(全右声道),如new SoundTransform(0.3,-1.0);
    _channel.soundTransform = transform;

    //视频播放
    public function ActionScriptDemo()
    {
     _video = new Video(160,120);
     _duration = 0;
     _playbackTime = new TextField();
     _playbackTime.autoSize = "left";
     _playbackTime.y = 120;
     
     var connection:NetConnection = new NetConnection();  //定义数据源
     connection.connect(null);  //null用于渐进式下载的视频
     
     var client:Object = new Object();  //定义回调函数
     client.onMetaData = onMetaData;
     
     _stream = new NetStream(connection);  //取回/加载数据
     _stream.client = client;  //加载完后会自动调用onMetaData回调方法
     _video.attachNetStream(_stream);  //把数据流附加到video对像进行转换
     _stream.play("1.flv");  //播放视频
     
     addChild(_video);
     addChild(_playbackTime);
     addEventListener(Event.ENTER_FRAME,onEnterFrame);
    }
      private function onMetaData(data:Object):void
    {
     _duration = data.duration;  //总长
    }
    private function onEnterFrame(data:Event):void
    {
     if(_duration > 0 && _stream.time >0)
     {
      _playbackTime.text = Math.round(_stream.time) + " / " + Math.round(_duration);
     }
    }

    //视频缩放
    _stream.addEventListener(NetStatusEvent.NET_STATUS,onStatus);  //视频下载完后调整视频大小
    private function onStatus(event:NetStatusEvent):void
    {
     if(_video.videoWidth > 0 && _video.width != _video.videoWidth)
     {
      _video.width = _video.videoWidth;
      _video.height = _video.videoHeight;
     }
    }

    //视频播放/暂停
    _playPauseButton.addEventListener(MouseEvent.CLICK,onPlayPause);  //_playPauseButton:Sprite
    private function onPlayPause(event:MouseEvent):void
    {
     _stream.togglePause();
    }

    //停止视频:当使用pause()时,视频只支暂停,而且数据还是会持继下载。如果想完全停止视频的下载,就使用close()方法。

    //控制播放时间:使用videoStream.seek(),如videoStream.seek(5)表示从开头前进5秒。


    /*第17章 存储持久化数据*/
    本地共享对象(local shared object,LSO),远程共享对象(remote shared object,RSO)

    //把数据写入共享对象
    var example:SharedObject = SharedObject.getLocal("example");
    example.data.someData = "a valeu";  //把一个名为someData的属性存在example共享对象的data中


    //序列化自定义类
    //自定义类:
    package ExtendPackage
    {
     public class Person
     {
      private var _name:String;
      private var _age:int;
      public function Person(name:String, age:int)
      {
       _name = name;
       _age = age;
      }
      public function toString():String
      {
       return _name + " is " + _age + " years old";
      }
     }
    }
    //主程序
    package
    {
     import ExtendPackage.Person;
     import flash.display.Sprite;
     import flash.net.SharedObject;
     import flash.net.registerClassAlias;
     
     public class ActionScriptDemo extends Sprite
     {
      public function ActionScriptDemo()
      {
       registerClassAlias("ExtendPackage.Person",Person);
       var example:SharedObject = SharedObject.getLocal("example");
       if(example.data.person == undefined)
       {
        trace("first time,saving person instance");
        var person:Person = new Person("terry",25);
        example.data.person = person;
       }
       else
       {
        trace("person instance already saved, using stored values");
       }
       trace(example.data.person.toString());
      }
     }
    }

    /*第18章 与其它影片通信 */

    /*第19章 发送和加载数据*/

    /*第20章 XML*/
    //创建XML对象
    var name:String = "terry";
    var score:int = 1000;
    var str:String = "<gamescore><name>" + name + "</name><score>" + score + "</score></gamescore>";
    var example:XML = new XML(str);
    //以上两句等价于:var example:XML = <gamescore><name>{name}</name><score>{score}</score></gamescore>

    //添加元素
    var example:XML = <example/>
    example.newElement = <newElement/>;
    //等价于:example.newElement = "";
    trace(example);

    //动态结点名(把.改成[];当结点名中有-号时也要使用[]而不能使用.)
    var example:XML = <example/>
    var id:int = 10;
    example["user" + id] = "";  //把user10做为结点名
    trace(example);

    //播入结点
    var example:XML = <example/>
    example.two = "";
    example = example.insertChildBefore(example.two,<one />);
    example = example.insertChildAfter(example.two,<three />);
    trace(example);
    //还有appendChild(),prependChild,insertChildAfter,insertChildBefore

    //添加属性到结点(当属性名中有-号时也要使用[]而不能使用.)
    var example:XML = <example><someElement/></example>;
    example.someElement.@number = 12.1;
    example.someElement.@string = "example";
    example.someElement.@boolean = true;
    example.someElement.@array = ["a",null,7,undefined,"c"];   
    trace(example);
    //输出
    <example>
      <someElement number="12.1" string="example" boolean="true" array="a,,7,,c"/>
    </example>
    //动态属性名使用[]

    //读取XML树中的元素
    var menu:XML = <menu>
            <menuitem label="file">
             <menuitem label="new"/>
            </menuitem>
            <menuitem label="help">
             <menuitem label="about"/>
            </menuitem>
            this is a text node
           </menu>;
    for each(var element:XML in menu.elements())
    {
     trace(element.@label);
    }
    //显示file和help,并没有显示new和about,因为它们并非menu元素的直接子结点。要遍历整棵树,需要用到递归函数(for each改成walk(menu)):
    private function walk(node:XML):void  //类型也是XML
    {
     for each(var element:XML in node.elements())
     {
      trace(element.@label);
      walk(element);
     }
    }

    //通过名称查找元素
    var fruit:XML = <fruit><name>Apple</name></fruit>;
    trace(fruit.name);
    var author:XML = <author><name><firstname>terry</firstname></name></author>;
    trace(author.name.firstname);
    //如果不知道详细路径可以使用双点运算符,如:author..firstname
    //当数据项不至一条时,可以使用索引式。如:author.name[0].firstname
    //计算元素的数目:author.name.length();

    //读取文本节点及其值
    var example:XML = <example>
            <string>ookk</string>
            <bool>true</bool>
            <bool2>false</bool2>
            <integer>12</integer>
            <number>.9</number>
            </example>;
        
    var string:String = example.string.toString();
    var bool:Boolean = Boolean(example.bool);
    var bool2:Boolean = Boolean(example.bool2);
    var integer:int = int(example.integer);
    var number:Number = example.number;
    trace(string);
    trace(bool);
    trace(bool2);  //输出true
    trace(integer);
    trace(number);
    //上面的bool2并没有像想象中一样会输出false,而是输出了true。正确的做法应该是:
    var bool2:Boolean = example.bool2.toLowerCase() == "true";

    //混合元素取文本:
    var fruit:XML = <fruit>
            <name>Apple</name>
            an apple a day...
            </fruit>;
    var value:String = fruit.toString();
    trace(value);
    //输出:
    <fruit>
      <name>Apple</name>
      an apple a day...
    </fruit>
    //可以用text(),只返回元素的文本
    for each(var textNode:XML in fruit.text())
    {
     trace(textNode);
    }
    //输出:an apple a day...


    //读取元素的属性
    var fruit:XML = <fruit name="apple" color="red" />;
    var attrs:XMLList = fruit.attributes();
    trace(attrs[0]);  //apple
    trace(attrs[1]);  //red
    trace(attrs[1].name());  //color
    trace(fruit.@color);  //red
    trace(fruit.attribute("color"));  //red

    //移除元素、文本节点和属性
    var example:XML = <example>
            <fruit color="red">apple</fruit>
            <vegetable color="green">broccoli</vegetable>
            <dairy color="white">milk</dairy>
            </example>;
    delete example.fruit.@color;  //属性
    delete example.dairy;  //元素
    delete example.vegetable.text()[0];  //文本节点
    trace(example);
    //输出:
    <example>
      <fruit>apple</fruit>
      <vegetable color="green"/>
    </example>

    //循环把全部属性去掉
    var example:XML = <example><fruit color="red" name="apple" /></example>;
    var attrs:XMLList = example.fruit.@*;  //取得fruit的属性列表
    for(var i:int = attrs.length()-1;i>=0;i--)  //从数组尾端开始,可以避免循环时数组索引发生变化的问题
    {
     delete attrs[i];
    }
    trace(example);

    //读取XML
    public function ActionScriptDemo()
    {
     var loader:URLLoader = new URLLoader();
     loader.load(new URLRequest("test.xml"));
     loader.addEventListener(Event.COMPLETE,handleComplete);
    }
    private function handleComplete(event:Event):void{
     try
     {
      var example:XML = new XML(event.target.data);
      trace(example);
     }
     catch(e:TypeError)
     {
      trace("error: " + e.message);
     }
    }

    //在xml中使用html和特殊字符,使用<![CDATA[。。。]]>
    <test>
      <name>terry</name>
      <html><![CDATA[mystrbegin a < b mystrend]]></html>
    </test>


    /*第21章 Web Services 和 Flash Remoting*/
    /*第22章 建立集成应用程序*/
    /*第23章 文件管理*/
    /*第24章 Socket编程*/

  • 相关阅读:
    JAVA BigDecimal 小数点处理
    对 Element UI table中数据进行二次处理
    Kettle-User Defined Java Class使用-大写转换
    多线程-同步函数
    多线程-银行分批存款
    多线程-并发卖票
    多线程-控制两个线程交替打印
    ztree-可拖拽可编辑的树
    ztree-编辑节点(树节点添加,删除,修改)
    ztree-拖拽(排序树)
  • 原文地址:https://www.cnblogs.com/vipcjob/p/1701651.html
Copyright © 2020-2023  润新知