Tips on ActionScript

[2008/3/17新規] [2008/5/10更新]

もくじ

Flex と Flash

このページでは Tips on HaXe で紹介した Flash9 向け haXe サンプルコードに対応する元々の ActionScript3 サンプルコードを紹介している。

flex3 SDK のインストール

Adobe のサイトの Flex3 ダウンロードの最下段に Flex3 SDK for all Platforms があり、ライセンス条項に同意するとそれがダウンロードできる。基本的に Java で書かれているので Java 実行環境がサポートされているプラットフォームであれば利用可能である。ここの Mac OS X では以下のようにした。

$ cd ~/import/lang/flex3
$ unzip flex_sdk_3.zip
$ cd /usr/local
$ sudo ln -s ~/import/lang/flex3 .

ActionScript3 サンプルコード for Flash9

as3/makefile
MXMLC=/usr/local/flex3/bin/mxmlc $(MXMLCFLAGS) $(MXMLC_EXTRA_LIBS)

SWFS=\
ExampleText.swf	\
ExampleHTMLText.swf	\
ExampleScrollText.swf	\
ExampleUserInputText.swf	\
ExampleCSSHTMLText.swf	\
ExampleAdvancedText.swf	\
ExampleRegExp.swf	\
ExampleXML.swf	\
\
ExampleMovieClip0.swf	\
ExampleMovieClip.swf	\
ExampleDraggableMovieClip.swf	\
ExampleDisplayList.swf	\
ExampleAnimation.swf	\
ExampleExternalMovieClip.swf	\
ExampleGeom.swf	\
\
ExampleSystem.swf	\
ExampleCapabilities.swf	\
\
ExampleMicrophone.swf	\
ExampleCamera.swf	\
ExampleURLSound.swf	\
ExampleURLVideo.swf	\

all: $(SWFS) $(SWFS:.swf=.html)

%.swf: %.as
	$(MXMLC) -output $@ -default-size 640 480 -default-frame-rate 10 -default-background-color 0xffffff $<

%.html: %.swf
	echo "<html><head><title>$<</title></head><body><embed src=\"$<\" width=\"640\" height=\"480\" allowfullscreen=\"true\" type=\"application/x-shockwave-flash\"/></body></html>" > $@

clean: clean.htmls
	rm -f $(SWFS)

clean.htmls:
	rm -f $(SWFS:.swf=.html)

distclean:
	rm -f $(SWFS:.swf=.as~)

テキスト関係

as3/ExampleText.as
package {
import flash.display.Sprite;
import flash.text.TextField;
//import flash.text.TextFieldAutoSize;

public class ExampleText extends Sprite {
  static protected var myTextBox:TextField = new TextField();
  static protected var myText:String = "Hello World!";

  public function ExampleText() {
    super();
    //myTextBox.autoSize = TextFieldAutoSize.LEFT;
    addChild(myTextBox);
    myTextBox.text = myText;
  }
}

}
[SWF]
as3/ExampleHTMLText.as
package {
import flash.text.TextField;
import flash.display.Sprite;

public class ExampleHTMLText extends Sprite {
  static protected var myTextBox:TextField = new TextField();
  static protected var myText:String = "<p>これは<u>HTML</u>テキストとして<i>描画</i>すべき<b>内容</b>です。</p>";

  public function ExampleHTMLText() {
    super();
    myTextBox.width = 160;
    myTextBox.height = 120;
    myTextBox.multiline = true;
    myTextBox.wordWrap = true;
    myTextBox.border = true;
    addChild(myTextBox);
    myTextBox.htmlText = myText;
  }
}

}
[SWF]
as3/ExampleScrollText.as
package {
import flash.text.TextFormat;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.text.TextField;

public class ExampleScrollText extends Sprite {
  static protected var myTextBox:TextField = new TextField();
  static protected var myText:String = "マウスをクリックするとテキストが上にスクロールするようになっています。テキストが下にスクロールするようにはなっておりません。";

  public function ExampleScrollText() {
    super();
    myTextBox.text = myText;
    myTextBox.width = 160;
    myTextBox.height = 30;
    myTextBox.multiline = true;
    myTextBox.wordWrap = true;
    myTextBox.background = true;
    myTextBox.border = true;
    var format:TextFormat = new TextFormat();
    format.font = "Verdana";
    format.color = 0xFF0000;
    format.size = 10;
    myTextBox.defaultTextFormat = format;
    myTextBox.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownScroll);
    addChild(myTextBox);
    myTextBox.htmlText = myText;
  }
  public function mouseDownScroll(event:MouseEvent):void {
    myTextBox.scrollV++;
  }
}

}
[SWF]
as3/ExampleUserInputText.as
package {
import flash.events.TextEvent;
import flash.text.TextFieldType;
import flash.display.Sprite;
import flash.text.TextField;

public class ExampleUserInputText extends Sprite {
  static protected var myTextBox:TextField = new TextField();
  static protected var myOutputBox:TextField = new TextField();
  static protected var myText:String = "テキストが追加されると捕捉されます。";

  public function ExampleUserInputText() {
    super();
    captureText();
  }
  public function captureText():void {
    myTextBox.type = TextFieldType.INPUT;
    myTextBox.background = true;
    myTextBox.width = 160;
    myTextBox.multiline = true;
    myTextBox.wordWrap = true;
    myTextBox.border = true;
    addChild(myTextBox);
    myTextBox.text = myText;
    myTextBox.addEventListener(TextEvent.TEXT_INPUT, textInputCapture);
  }
  public function textInputCapture(event:TextEvent):void {
    var str:String = myTextBox.text;
    createOutputBox(str);
  }
  public function createOutputBox(str:String):void {
    myOutputBox.background = true;
    myOutputBox.width = 160;
    myOutputBox.multiline = true;
    myOutputBox.wordWrap = true;
    myOutputBox.border = true;
    myOutputBox.x = 160;
    addChild(myOutputBox);
    myOutputBox.text = str;
  }
}

}
[SWF]
as3/ExampleCSSHTMLText.as
package {
import flash.net.URLRequest;
import flash.text.StyleSheet;
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.Event;
import flash.net.URLLoader;
import flash.text.TextFieldAutoSize;

public class ExampleCSSHTMLText extends Sprite {
  protected var loader:URLLoader;
  protected var field:TextField;
  protected var exampleText:String;

  public function ExampleCSSHTMLText():void {
    super();
    iam();
  }
  public function iam():void {
    field = new TextField();
    field.width = 300;
    field.autoSize = TextFieldAutoSize.LEFT;
    field.wordWrap = true;
    addChild(field);
    var req:URLRequest = new URLRequest("ExampleCSSHTMLText.css");
    loader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, onCSSFileLoaded);
    loader.load(req);
    exampleText = "<h1>これがヘッドライン</h1>" +
"<p>これはパラグラフ。これは、" + 
"<span class='bluetext'>青色の属性の範囲</span>。</p>";
  }
  public function onCSSFileLoaded(event:Event):void {
    var sheet:StyleSheet = new StyleSheet();
    sheet.parseCSS(loader.data);
    field.styleSheet = sheet;
    field.htmlText = exampleText;
  }
}

}
[SWF]
as3/ExampleAdvancedText.as
package  {
import flash.text.TextColorType;
import flash.text.CSMSettings;
import flash.text.TextFormat;
import flash.text.TextRenderer;
import flash.events.MouseEvent;
import flash.text.FontStyle;
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.Event;
import flash.text.AntiAliasType;
import flash.text.TextFieldAutoSize;

public class ExampleAdvancedText extends Sprite {
  [Embed(source='lib/Vera.ttf',	// Embedメタデータタグ (devguide_flex3, P.497)
         fontName='myFont',
         mimeType='application/x-font',
         unicodeRange='U+0041-U+005A,U+0061-U+007A')]
  private var myFont:Class;

  public function ExampleAdvancedText():void {
    super();
    var format:TextFormat = new TextFormat();
    format.color = 0x336699;
    format.size = 48;		// フォントサイズ
    format.font = "myFont";	// フォント名
    var myText:TextField = new TextField();
    myText.embedFonts = true;	// 埋め込みフォント
    myText.autoSize = TextFieldAutoSize.LEFT;
    myText.antiAliasType = AntiAliasType.ADVANCED; // TextRendererを使用する場合
    myText.defaultTextFormat = format;
    myText.selectable = false;
    myText.mouseEnabled = true;
    myText.text = "Hello World?";
    addChild(myText);
    myText.addEventListener(MouseEvent.CLICK, clickHandler);
  }
  protected function clickHandler(event:Event):void {
    var myAntiAliasSettings:CSMSettings = new CSMSettings(
      48,	// fontSize;		ターゲットとなるフォントサイズ
      2,	// insideCutoff;	これを大きくすると細く滑らかになる
      -0	// outsizeCutoff;	これを大きくすると太く滑らかになる
    );
    var myAliasTable:Array = [myAntiAliasSettings];
    TextRenderer.setAdvancedAntiAliasingTable(
      "myFont", FontStyle.REGULAR,	// ターゲットとなるフォント名とスタイル
      TextColorType.DARK_COLOR,		// 線が濃い(DARK_COLOR)か、薄い(LIGHT_COLOR)か
      myAliasTable			// 所望の CSMSettings
    );
  }
}

}
[SWF]

正規表現

as3/ExampleRegExp.as
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;

public class ExampleRegExp extends Sprite {
  static protected var myTextBox:TextField = new TextField();
  static protected var myText:String = "";

  public function ExampleRegExp():void {
    var regexp:String;
    var pattern:RegExp;
    var target:String;
    var result:Boolean;
    var dest:String;

    super();
    myTextBox.autoSize = TextFieldAutoSize.LEFT;
    addChild(myTextBox);

    regexp = "ABC";
    pattern = new RegExp(regexp,"i");
    target = "abc";
    dest = "efg";
    trace("[regexp]" + regexp + " " +
      "[target]" + target + " " +
      "[match]" + (result = pattern.test(target)) + " " +
      "[replace]" + target.replace(pattern,dest));

    regexp = "<P>.*?</P>";
    pattern = new RegExp(regexp,"is");
    target = "<p>paragraph1\n</p><p>paragraph2</p>";
    dest = "";
    trace("[regexp]" + regexp + " " +
      "[target]" + target + " " +
      "[match]" + (result = pattern.test(target)) + " " +
      "[replace]" + target.replace(pattern,dest));

    regexp = "(sh\\w*)";
    pattern = new RegExp(regexp,"g");
    target = "she sells seashells by the seashore.\n";
    dest = "($1)";
    trace("[regexp]" + regexp + " " +
      "[target]" + target + " " +
      "[match]" + (result = pattern.test(target)) + " " +
      "[replace]" + target.replace(pattern,dest));
  }
  private function trace(text:String):void {
    myText += text + "\n";
    myTextBox.text = myText;
  }
}

}
[SWF]

XML

as3/ExampleXML.as
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;

public class ExampleXML extends Sprite {
  static protected var myTextBox:TextField = new TextField();
  static protected var myText:String = "";

  public function ExampleXML():void {
    super();
    myTextBox.autoSize = TextFieldAutoSize.LEFT;
    addChild(myTextBox);

    var myText:String = "\
<order>\
  <item id='1'>\
    <menuName>burger</menuName>\
    <price>3.95</price>\
  </item>\
  <item id='2'>\
    <menuName>fries</menuName>\
    <price>1.45</price>\
  </item>\
</order>\
";
    var myXML:XML = new XML(myText);

    trace("myXML.item[0].menuName: " + myXML.item[0].menuName);
    trace("myXML.item.(@id==2).menuName: " + myXML.item.(@id==2).menuName);
    trace("myXML.item.(menuName==\"burger\").price: " + myXML.item.(menuName=="burger").price);
    trace("");

    myXML.appendChild(new XML("\
  <item id=\"3\">\
    <menuName>medium cola</menuName>\
    <price>1.25</price>\
  </item>\
"));

    trace("myXML.item[2].menuName: " + myXML.item[2].menuName);
    trace("myXML.item.(@id==3).menuName: " + myXML.item.(@id==3).menuName);
    trace("myXML.item.(price==1.25).menuName: " + myXML.item.(price==1.25).menuName);

    trace("");

    myXML.item[0].menuName="regular burger";
    myXML.item[1].menuName="small fries";
    myXML.item[2].menuName="medium cola";
    myXML.item.(menuName=="regular burger").@quantity = "2";
    myXML.item.(menuName=="small fries").@quantity = "2";
    myXML.item.(menuName=="medium cola").@quantity = "2";

    var total:Number = 0;
    for each (var property:XML in myXML.item) {
      var q:int = Number(property.@quantity);
      var p:Number = Number(property.price);
      var itemTotal:Number = q * p;
      total += itemTotal;
      trace("menuName: " + property.menuName + " " +
        "price: " + property.price + " * " +
         "@quantity: " + q + " = " + itemTotal.toFixed(2));
    }
    trace("Total: $" + total.toFixed(2));
  }
  private function trace(text:String):void {
    myText += text + "\n";
    myTextBox.text = myText;
  }
}

}
[SWF]

ディスプレイ関係

as3/ExampleMovieClip0.as
package {
import flash.display.MovieClip;

public class ExampleMovieClip0 extends MovieClip {
  public function ExampleMovieClip0():void {
    graphics.lineStyle(1, 0xFF0000, 100);
    graphics.beginFill(0x0000FF, 100);
    graphics.moveTo(100, 100);
    graphics.lineTo(200, 100);
    graphics.lineTo(200, 200);
    graphics.lineTo(100, 200);
    graphics.lineTo(100, 100);
    graphics.endFill();
  }
}

}
[SWF]
as3/ExampleMovieClip.as
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;

public class ExampleMovieClip extends MovieClip {
  public function ExampleMovieClip():void {
    var mc:MovieClip = new MovieClip();
    addChild(mc);
    mc.graphics.lineStyle(1, 0x000000, 100);
    mc.graphics.beginFill(0xFF0000, 100);
    mc.graphics.moveTo(100, 100);
    mc.graphics.lineTo(200, 100);
    mc.graphics.lineTo(200, 200);
    mc.graphics.lineTo(100, 200);
    mc.graphics.lineTo(100, 100);
    mc.graphics.endFill();
    mc.addEventListener(MouseEvent.MOUSE_DOWN, function(ev:MouseEvent):void { mc.startDrag(false); });
    mc.addEventListener(MouseEvent.MOUSE_UP, function(ev:MouseEvent):void { mc.stopDrag(); });
  }
}

}
[SWF]
as3/ExampleDraggableMovieClip.as
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;

public class ExampleDraggableMovieClip extends MovieClip {
  public function ExampleDraggableMovieClip():void {
    super();
    graphics.lineStyle(1, 0x000000, 100);
    graphics.beginFill(0xFF0000, 100);
    graphics.moveTo(100, 100);
    graphics.lineTo(200, 100);
    graphics.lineTo(200, 200);
    graphics.lineTo(100, 200);
    graphics.lineTo(100, 100);
    graphics.endFill();
    addEventListener(MouseEvent.MOUSE_DOWN, onPress);
    addEventListener(MouseEvent.MOUSE_UP, onRelease);
  }
  public function onPress(ev:MouseEvent):void { startDrag(false); }
  public function onRelease(ev:MouseEvent):void { stopDrag(); }
}

}
[SWF]
as3/Ball0.as
package {
import flash.text.TextField;
import flash.display.MovieClip;

public class Ball0 extends MovieClip {
  public function Ball0(color:int, label:String):void {
    super();
    graphics.lineStyle(1, 0x000000, 100);
    graphics.beginFill(color, 100);
    graphics.drawCircle(x, y, 30);
    graphics.endFill();
    var myTextField:TextField = new TextField();
    myTextField.text = label;
    addChild(myTextField);
  }
}

}
as3/ExampleDisplayList.as
package  {
import flash.events.MouseEvent;
import flash.display.Sprite;
import Ball0;

public class ExampleDisplayList extends Sprite {
  protected var ball_A:Ball0;
  protected var ball_B:Ball0;
  protected var ball_C:Ball0;

  public function ExampleDisplayList():void {
    super();
    ball_A = new Ball0(0xFFCC00, "a");
    ball_A.name = "ball_A";
    ball_A.x = 20;
    ball_A.y = 20;
    addChild(ball_A);
    ball_B = new Ball0(0xFFCC00, "b");
    ball_B.name = "ball_B";
    ball_B.x = 70;
    ball_B.y = 20;
    addChild(ball_B);
    ball_C = new Ball0(0xFFCC00, "c");
    ball_C.name = "ball_C";
    ball_C.x = 40;
    ball_C.y = 60;
    addChildAt(ball_C, 1);
    addEventListener(MouseEvent.MOUSE_DOWN, onPress);
    addEventListener(MouseEvent.MOUSE_UP, onRelease);
    x = y = 20;
  }
  public function onPress(ev:MouseEvent):void { removeChild(ball_C); startDrag(false); }
  public function onRelease(ev:MouseEvent):void { stopDrag(); addChild(ball_C); }
}

}
[SWF]
as3/Ball1.as
package {
import flash.text.TextField;
import flash.display.MovieClip;
import flash.events.Event;

public class Ball1 extends MovieClip {
  protected var d:Number;
  public function Ball1(color:int, label:String):void {
    super();
    graphics.lineStyle(1, 0x000000, 100);
    graphics.beginFill(color, 100);
    graphics.drawCircle(x, y, 30);
    graphics.endFill();
    var myTextField:TextField = new TextField();
    myTextField.text = label;
    addChild(myTextField);
    d = -0.05;
    addEventListener(Event.ENTER_FRAME, animate);
  }
  public function animate(ev:Event):void {
    alpha += d;
    if (alpha < 0) { d = 0.05; }
    else if (alpha > 1) { d = -0.05; }
  }
}

}
as3/ExampleAnimation.as
package {
import flash.events.MouseEvent;
import flash.display.Sprite;
import Ball1;

public class ExampleAnimation extends Sprite {
  protected var ball_A:Ball1;
  protected var ball_B:Ball1;
  protected var ball_C:Ball1;

  public function ExampleAnimation():void {
    super();
    ball_A = new Ball1(0xFFCC00, "a");
    ball_A.name = "ball_A";
    ball_A.x = 20;
    ball_A.y = 20;
    addChild(ball_A);
    ball_B = new Ball1(0x00FFCC, "b");
    ball_B.name = "ball_B";
    ball_B.x = 70;
    ball_B.y = 20;
    addChild(ball_B);
    ball_C = new Ball1(0xCC00FF, "c");
    ball_C.name = "ball_C";
    ball_C.x = 40;
    ball_C.y = 60;
    addChildAt(ball_C, 1);
    addEventListener(MouseEvent.MOUSE_DOWN, onPress);
    addEventListener(MouseEvent.MOUSE_UP, onRelease);
    x = y = 20;
  }
  public function onPress(ev:MouseEvent):void { removeChild(ball_C); startDrag(false); }
  public function onRelease(ev:MouseEvent):void { stopDrag(); addChild(ball_C); }
}

}
[SWF]
as3/ExampleExternalMovieClip.as
package  {
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.events.Event;
import Ball1;

public class ExampleExternalMovieClip extends Sprite {
  protected var ball_A:Ball1;
  protected var ball_B:Ball1;
  protected var ball_C:Ball1;

  public function ExampleExternalMovieClip():void {
    super();
    ball_A = new Ball1(0xFFCC00, "a");
    ball_A.name = "ball_A";
    ball_A.x = 20;
    ball_A.y = 20;
    addChild(ball_A);
    ball_B = new Ball1(0x00FFCC, "b");
    ball_B.name = "ball_B";
    ball_B.x = 70;
    ball_B.y = 20;
    addChild(ball_B);
    ball_C = new Ball1(0xCC00FF, "c");
    ball_C.name = "ball_C";
    ball_C.x = 40;
    ball_C.y = 60;
    addChildAt(ball_C, 1);
    addEventListener(MouseEvent.MOUSE_DOWN, onPress);
    addEventListener(MouseEvent.MOUSE_UP, onRelease);
    x = y = 20;

    var ldr:Loader = new Loader();
    var urlReq:URLRequest = new URLRequest("ExampleDraggableMovieClip.swf");
    ldr.load(urlReq);
    ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
    addChild(ldr);
  }
  public function onPress(ev:MouseEvent):void { removeChild(ball_C); startDrag(false); }
  public function onRelease(ev:MouseEvent):void { stopDrag(); addChild(ball_C); }
  public function loaded(event:Event):void { addChild(event.target.content); }
}

}
[SWF]

ジオメトリ関係

as3/Ball.as
package {
import flash.display.GradientType;
import flash.display.MovieClip;
import flash.geom.Matrix;
import flash.text.TextField;
import flash.events.Event;
import flash.display.SpreadMethod;
import flash.display.InterpolationMethod;

public class Ball extends MovieClip {
  protected var d:Number;
  public function Ball(color:int, label:String):void {
    super();
    graphics.lineStyle(1, 0x000000, 100);
    var colors:Array = [color, 0xFFFFFF];
    var alphas:Array = [1, 1];
    var ratios:Array = [0, 255];
    var matrix:Matrix = new Matrix();
    matrix.createGradientBox(
      /*Width:			*/60,
      /*Height:			*/60,
      /*Rotation:		*/0,
      /*X:			*/-30,
      /*Y:			*/-30
    );
    graphics.beginGradientFill(
      /*GradientType:		*/GradientType.RADIAL,
      /*colors:			*/colors,
      /*alphas:			*/alphas,
      /*ratios:			*/ratios,
      /*Matrix:			*/matrix,
      /*SpreadMethod:		*/SpreadMethod.PAD,
      /*InterpolationMethod:	*/InterpolationMethod.LINEAR_RGB,
      /*focalPointRatio:	*/0
    );
    graphics.drawCircle(x, y, 30);
    graphics.endFill();
    var myTextField:TextField = new TextField();
    myTextField.text = label;
    addChild(myTextField);
    d = -0.05;
    addEventListener(Event.ENTER_FRAME, animate);
  }
  public function animate(ev:Event):void {
    alpha += d;
    if (alpha < 0) { d = 0.05; }
    else if (alpha > 1) { d = -0.05; }
    var mat:Matrix = new Matrix();
    mat.scale(1-alpha, 1);
    mat.translate(x, y);
    transform.matrix = mat;
  }
}

}
as3/ExampleGeom.as
package {
import flash.events.MouseEvent;
import flash.display.Sprite;
import Ball;

public class ExampleGeom extends Sprite {
  protected var ball_A:Ball;
  protected var ball_B:Ball;
  protected var ball_C:Ball;

  public function ExampleGeom():void {
    super();
    ball_A = new Ball(0xFFCC00, "a");
    ball_A.name = "ball_A";
    ball_A.x = 20;
    ball_A.y = 20;
    addChild(ball_A);
    ball_B = new Ball(0x00FFCC, "b");
    ball_B.name = "ball_B";
    ball_B.x = 70;
    ball_B.y = 20;
    addChild(ball_B);
    ball_C = new Ball(0xCC00FF, "c");
    ball_C.name = "ball_C";
    ball_C.x = 40;
    ball_C.y = 60;
    addChildAt(ball_C, 1);
    addEventListener(MouseEvent.MOUSE_DOWN, onPress);
    addEventListener(MouseEvent.MOUSE_UP, onRelease);
    x = y = 20;
  }
  public function onPress(ev:MouseEvent):void { removeChild(ball_C); startDrag(false); }
  public function onRelease(ev:MouseEvent):void { stopDrag(); addChild(ball_C); }
}

}
[SWF]

システム関係

as3/ExampleSystem.as
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.system.System;
import flash.text.TextFieldAutoSize;

public class ExampleSystem extends Sprite {
  static protected var myTextBox:TextField = new TextField();
  static protected var myText:String = "System properties and Clipboard:\n";

  public function ExampleSystem():void {
    super();
    myTextBox.autoSize = TextFieldAutoSize.LEFT;
    addChild(myTextBox);
    myText += "  totalMemody:\t" + System.totalMemory + "\n";
    myText += "  useCodePage:\t" + System.useCodePage + "\n";
    myText += "  vmVersion:\t" + System.vmVersion + "\n";
    System.setClipboard(myText);
    myTextBox.text = myText;
  }
}

}
[SWF]
as3/ExampleCapabilities.as
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.system.Capabilities;
import flash.text.TextFieldAutoSize;

public class ExampleCapabilities extends Sprite {
  static protected var myTextBox:TextField = new TextField();
  static protected var myText:String = "Capabilities properties:\n";

  public function ExampleCapabilities():void {
    super();
    myTextBox.autoSize = TextFieldAutoSize.LEFT;
    addChild(myTextBox);
    myText += "  avHardwareDisable:\t" + Capabilities.avHardwareDisable + "\n";
    myText += "  hasAccessibility:\t" + Capabilities.hasAccessibility + "\n";
    myText += "  hasAudio:\t" + Capabilities.hasAudio + "\n";
    myText += "  hasAudioEncoder:\t" + Capabilities.hasAudioEncoder + "\n";
    myText += "  hasEmbeddedVideo:\t" + Capabilities.hasEmbeddedVideo + "\n";
    myText += "  hasIME:\t" + Capabilities.hasIME + "\n";
    myText += "  hasMP3:\t" + Capabilities.hasMP3 + "\n";
    myText += "  hasPrinting:\t" + Capabilities.hasPrinting + "\n";
    myText += "  hasScreenBroadcast:\t" + Capabilities.hasScreenBroadcast + "\n";
    myText += "  hasScreenPlayback:\t" + Capabilities.hasScreenPlayback + "\n";
    myText += "  hasStreamingAudio:\t" + Capabilities.hasStreamingAudio + "\n";
    myText += "  hasStreamingVideo:\t" + Capabilities.hasStreamingVideo + "\n";
    myText += "  hasTLS:\t" + Capabilities.hasTLS + "\n";
    myText += "  hasVideoEncoder:\t" + Capabilities.hasVideoEncoder + "\n";
    myText += "  isDebugger:\t" + Capabilities.isDebugger + "\n";
    myText += "  language:\t" + Capabilities.language + "\n";
    myText += "  localFileReadDisable:\t" + Capabilities.localFileReadDisable + "\n";
    myText += "  manufacturer:\t" + Capabilities.manufacturer + "\n";
    myText += "  os:\t" + Capabilities.os + "\n";
    myText += "  pixelAspectRatio:\t" + Capabilities.pixelAspectRatio + "\n";
    myText += "  playerType:\t" + Capabilities.playerType + "\n";
    myText += "  screenColor:\t" + Capabilities.screenColor + "\n";
    myText += "  screenDPI:\t" + Capabilities.screenDPI + "\n";
    myText += "  screenResolutionX:\t" + Capabilities.screenResolutionX + "\n";
    myText += "  screenResolutionY:\t" + Capabilities.screenResolutionY + "\n";
    myText += "  serverString:\t" + Capabilities.serverString + "\n";
    myText += "  version:\t" + Capabilities.version + "\n";
    myTextBox.text = myText;
  }
}

}
[SWF]

マルチメディア関係

as3/ExampleMicrophone.as
package {
import flash.media.Microphone;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;

public class ExampleMicrophone extends Sprite {
  static protected var myTextBox:TextField = new TextField();
  static protected var myText:String = "マイクをスピーカーに繋げます。\n";

  public function ExampleMicrophone():void {
    super();
    myTextBox.autoSize = TextFieldAutoSize.LEFT;
    addChild(myTextBox);
    myTextBox.text = myText;

    var mic:Microphone = Microphone.getMicrophone();
    mic.setUseEchoSuppression(true);
    mic.setLoopBack(true);
  }
}

}
[SWF]
as3/ExampleCamera.as
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.media.Video;
import flash.text.TextFieldAutoSize;
import flash.media.Camera;

public class ExampleCamera extends Sprite {
  static protected var myTextBox:TextField = new TextField();
  static protected var myText:String = "カメラをモニターに繋げます。\n";

  public function ExampleCamera():void {
    super();
    myTextBox.autoSize = TextFieldAutoSize.LEFT;
    addChild(myTextBox);
    myTextBox.text = myText;

    var cam:Camera = Camera.getCamera();
    var vid:Video = new Video();
    vid.attachCamera(cam);
    addChild(vid);
  }
}

}
[SWF]
as3/Label.as
package {
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;

public class Label extends Sprite {
  public var tf:TextField;
  public var bg:Sprite;
  protected var type:int;
  protected var state:int;
  protected var size:Array;
  [Embed(source="lib/webdings.ttf",fontName="Webdings",mimeType='application/x-font')]
  public var Webdings:Class;
  [Embed(source="lib/wingdings.ttf",fontName="Wingdings",mimeType='application/x-font')]
  public var Wingdings:Class;
  [Embed(source="lib/wingdings_2.ttf",fontName="Wingdings 2",mimeType='application/x-font')]
  public var Wingdings2:Class;
  [Embed(source="lib/wingdings_3.ttf",fontName="Wingdings 3",mimeType='application/x-font')]
  public var Wingdings3:Class;

  public function Label(label:String, tfm:TextFormat=null, type:*=null, state:*=null, size:Array=null):void {
    super();
    tf = new TextField();
    if (tfm != null)
      tf.defaultTextFormat = tfm;
    this.type = type;
    this.state = state;
    if (size != null) {
      this.size = size;
      tf.width = size[0] + 2*2;
      tf.height = size[1] + 2*2;
    }
    else
      tf.autoSize = TextFieldAutoSize.LEFT;
    tf.htmlText = label;
    switch (type) {
      case 1: {
        tf.type = TextFieldType.INPUT;
      } break;
    }
    switch (tfm.font) {
    case "Webdings":
    case "Wingdings":
    case "Wingdings 2":
    case "Wingdings 3":
      tf.embedFonts = true;
      break;
    default:
      tf.embedFonts = false;
      break;
    }
    bg = new Sprite();
    bgDraw();
    addChild(bg);
    addChild(tf);
  }
  public function bgDraw():void {
    var m:Number = tf.defaultTextFormat.leftMargin + tf.defaultTextFormat.rightMargin;
    var d:Number;
    var size:Array = (this.size != null) ? this.size : [tf.textWidth, tf.textHeight];
    var w:Number;

    switch(state) {
    case 2:case 3:	d = 2.0; break;
    default:		d = 4.0; break;
    }
    x = y = 4 - d;
    bg.graphics.clear();
    switch (type) {
    case 0: {
        switch(state) {
	case 1:		w = 2.0; break;
	default:	w = 1.0; break;
	}
        bg.graphics.lineStyle(0, 0xCCCCCC);
        bg.graphics.beginFill(0xCCCCCC);
        bg.graphics.drawRoundRect(d, d, size[0] + m + 2*2, size[1] + 2*2, 2*4);
        bg.graphics.lineStyle(w, 0xFFFFFF);
        bg.graphics.beginFill(0xFFFFFF);
        bg.graphics.drawRoundRect(0, 0, size[0] + m + 2*2, size[1] + 2*2, 2*4);
        bg.graphics.endFill();
      } break;
    case 1: {
        switch(state) {
	case 1:		w = 2.0; break;
	default:	w = 1.0; break;
	}
        bg.graphics.lineStyle(0, 0xCCCCCC);
        bg.graphics.beginFill(0xCCCCCC);
        bg.graphics.drawRect(d, d, size[0] + m + 2*2, size[1] + 2*2);
        bg.graphics.lineStyle(w, 0x000000);
        bg.graphics.beginFill(0xFFFFFF);
        bg.graphics.drawRect(0, 0, size[0] + m + 2*2, size[1] + 2*2);
        bg.graphics.endFill();
      } break;
    default: {
        switch(state) {
	case 1:		w = 4.0; break;
	default:	w = 2.0; break;
	}
        bg.graphics.lineStyle(0, 0xCCCCCC);
        bg.graphics.beginFill(0xCCCCCC);
        bg.graphics.drawRoundRect(d, d, size[0] + m + 2*2, size[1] + 2*2, 2*4);
        bg.graphics.lineStyle(w, 0x000000);
        bg.graphics.beginFill(0xFFFFFF);
        bg.graphics.drawRoundRect(0, 0, size[0] + m + 2*2, size[1] + 2*2, 2*4);
        bg.graphics.endFill();
      } break;
    }
  }
  public function setLabel(label:String):void {
    tf.htmlText = label;
    bgDraw();
  }
}

}
as3/ExampleURLSound.as
package {
import flash.display.DisplayObject;
import flash.net.URLRequest;
import flash.text.TextFormat;
import flash.events.MouseEvent;
import flash.display.SimpleButton;
import flash.media.Sound;
import flash.display.Sprite;
import flash.media.SoundChannel;

public class ExampleURLSound extends Sprite {
  protected var snd:Sound;
  protected var sndc:SoundChannel;
  protected var items:Array;
  protected var fs:Array;

  public function ExampleURLSound():void {
    super();
    var s:Number = 16.0;
    fs = [
      new TextFormat("Courier", s, 0x000000),
      new TextFormat("Webdings", s, 0x000000),
    ];
    items = [
      new Label("URL",	fs[0], 0, 0, [s*2, s]),
      new Label("",	fs[0], 1, 0, [s*32, s]),
      new SimpleButton(),
    ];
    transition();
    items[2].addEventListener(MouseEvent.CLICK, pbPlay);
    items[0].x = items[0].y = 4;
    layouts(0, [items[0], items[1], items[2]]);
    for each (var item:DisplayObject in items)
      addChild(item);
  }
  protected function layouts(type:int, items:Array):void {
    var i:int;

    switch (type) {
    case 0:
      for (i=1; i<items.length; i++) {
        items[i].x = items[i-1].x + items[i-1].getRect(this).width + 4;
        items[i].y = items[i-1].y;
      }
      break;
    case 1:
      for (i=1; i<items.length; i++) {
        items[i].x = items[i-1].x;
        items[i].y = items[i-1].y + items[i-1].getRect(this).height + 4;
      }
      break;
    }
  }
  protected function transition():void {
    items[2].upState      = new Label((snd!=null)?"\x55":"\x56", fs[1], 2, 0);
    items[2].overState    = new Label((snd!=null)?"\x55":"\x56", fs[1], 2, 1);
    items[2].downState    = new Label((snd!=null)?"\x55":"\x56", fs[1], 2, 2);
    items[2].hitTestState = new Label((snd!=null)?"\x55":"\x56", fs[1], 2);
  }
  public function pbPlay(event:MouseEvent):void {
    if (snd == null) {
      if (items[1].tf.text != null) {
        snd = new Sound(new URLRequest(items[1].tf.text));
        sndc = snd.play();
      }
    }
    else {
      sndc.stop();
      snd = null;
    }
    transition();
  }
}

}
[SWF]
as3/NetStreamClient.as
package {

public class NetStreamClient {
  public var duration:Number;

  public function NetStreamClient() {}
  public function onMetaData(info:Object):void {
    duration = info.duration;
  }
}
}
as3/ExampleURLVideo.as
package {
import flash.display.DisplayObject;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageScaleMode;
import flash.events.FullScreenEvent;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.events.MouseEvent;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.net.NetConnection;
import flash.net.NetStream;
//import flash.events.AsyncErrorEvent;
import flash.events.NetStatusEvent;
import flash.media.Video;
import flash.utils.Timer;
import flash.events.TimerEvent;

public class ExampleURLVideo extends Sprite {
  protected var start:Boolean;
  protected var pause:Boolean;
  protected var scale:Number;
  protected var nc:NetConnection;
  protected var ns:NetStream;
  protected var tm:Timer;
  protected var items:Array;
  protected var fs:Array;

  public function ExampleURLVideo():void {
    super();
    var s:Number = 16.0;
    fs = [
      new TextFormat("Courier", s, 0x000000),
      new TextFormat("Webdings", s, 0x000000),
    ];
    items = [
      new SimpleButton(),
      new SimpleButton(new Label("\x37", fs[1], 2, 0),
                       new Label("\x37", fs[1], 2, 1),
                       new Label("\x37", fs[1], 2, 2),
                       new Label("\x37", fs[1], 2)),
      new SimpleButton(new Label("\x38", fs[1], 2, 0),
                       new Label("\x38", fs[1], 2, 1),
                       new Label("\x38", fs[1], 2, 2),
                       new Label("\x38", fs[1], 2)),
      new Label("URL",	fs[0], 0, 0, [s*2, s]),
      new Label("",	fs[0], 1, 0, [s*24, s]),
      new SimpleButton(),
      new SimpleButton(new Label("\x4c", fs[1], 2, 0),
                       new Label("\x4c", fs[1], 2, 1),
                       new Label("\x4c", fs[1], 2, 2),
                       new Label("\x4c", fs[1], 2)),
      new SimpleButton(new Label("\x31", fs[1], 2, 0),
                       new Label("\x31", fs[1], 2, 1),
                       new Label("\x31", fs[1], 2, 2),
                       new Label("\x31", fs[1], 2)),
      new Video(),
      new TextField(),
    ];
    start = pause = false;
    scale = 1;
    transition_pause();
    transition_start();
    transition();
    items[0].addEventListener(MouseEvent.CLICK, pbPause);
    items[1].addEventListener(MouseEvent.CLICK, pbRew);
    items[2].addEventListener(MouseEvent.CLICK, pbFF);
    items[5].addEventListener(MouseEvent.CLICK, pbStart);
    items[6].addEventListener(MouseEvent.CLICK, pbScaleVideo);
    items[7].addEventListener(MouseEvent.CLICK, pbFullScreen);
    items[9].autoSize = TextFieldAutoSize.LEFT;
    items[0].x = items[0].y = 4;
    layouts(0, [items[0], items[1], items[2], items[3], items[4], items[5], items[6], items[7]]);
    layouts(1, [items[0], items[8], items[9]]);
    for each (var item:DisplayObject in items)
      addChild(item);
    nc = new NetConnection();
    nc.connect(null);
    ns = new NetStream(nc);
    //ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
    ns.addEventListener(NetStatusEvent.NET_STATUS, statusHandler);
    ns.client = new NetStreamClient();
    items[8].attachNetStream(ns);
    items[8].smoothing = true;
    tm = new Timer(1000, 0);
    tm.addEventListener(TimerEvent.TIMER, timerHandler);
    stage.align = StageAlign.TOP_LEFT;
    stage.scaleMode = StageScaleMode.NO_SCALE;
  }
  protected function layouts(type:int, items:Array):void {
    var i:int;

    switch (type) {
    case 0:
      for (i=1; i<items.length; i++) {
        items[i].x = items[i-1].x + items[i-1].getRect(this).width + 4;
        items[i].y = items[i-1].y;
      }
      break;
    case 1:
      for (i=1; i<items.length; i++) {
        items[i].x = items[i-1].x;
        items[i].y = items[i-1].y + items[i-1].getRect(this).height + 4;
      }
      break;
    }
  }
  protected function transition_pause():void {
    items[0].upState      = new Label(pause?"\x34":"\x3b", fs[1], 2, 0);
    items[0].overState    = new Label(pause?"\x34":"\x3b", fs[1], 2, 1);
    items[0].downState    = new Label(pause?"\x34":"\x3b", fs[1], 2, 2);
    items[0].hitTestState = new Label(pause?"\x34":"\x3b", fs[1], 2);
  }
  protected function transition_start():void {
    items[5].upState      = new Label(start?"\xb7":"\xb8", fs[1], 2, 0);
    items[5].overState    = new Label(start?"\xb7":"\xb8", fs[1], 2, 1);
    items[5].downState    = new Label(start?"\xb7":"\xb8", fs[1], 2, 2);
    items[5].hitTestState = new Label(start?"\xb7":"\xb8", fs[1], 2);
  }
  protected function transition():void {
    items[9].text = "";
    if (ns != null) {
      items[9].text += "bytes: " + ns.bytesLoaded + "/" + ns.bytesTotal + "\n";
      items[9].text += "time: " + ns.time + "/" + ns.client.duration + "\n";
      if (items[8].videoWidth!=0 && items[8].videoHeight!=0 &&
          (items[8].width != items[8].videoWidth*scale ||
           items[8].height != items[8].videoHeight*scale)) {
        items[8].width = items[8].videoWidth*scale;
        items[8].height = items[8].videoHeight*scale;
        layouts(1, [items[0], items[8], items[9]]);
      }
    }
  }
  public function statusHandler(event:NetStatusEvent):void {
    switch (event.info.code) {
    case "NetStream.Buffer.Full":
    case "NetStream.Buffer.Empty":
      break;
    default:
      items[9].text += event.info.code + "\n";
      break;
    }
  }
  public function timerHandler(event:TimerEvent):void {
    transition();
  }
  public function pbStart(event:MouseEvent):void {
    if (!start) {
      if (items[4].tf.text != null) {
        ns.play(items[4].tf.text);
        start = true;
        tm.start();
        transition_start();
      }
    }
    else {
      ns.close();
      start = pause = false;
      tm.stop();
      transition_start();
      transition_pause();
    }
    transition();
  }
  public function pbPause(event:MouseEvent):void {
    if (start) {
      ns.togglePause();
      pause = !pause;
      transition_pause();
    }
  }
  public function pbRew(event:MouseEvent):void {
    if (start)
      ns.seek((ns.time>=10)?ns.time-10:0);
  }
  public function pbFF(event:MouseEvent):void {
    if (start)
      ns.seek(ns.time+10);
  }
  public function pbScaleVideo(event:MouseEvent):void {
    switch (scale) {
    case .5: scale = 1; break;
    case 1: scale = 1.5; break;
    case 1.5: scale = 2; break;
    case 2:
      scale = Math.min((stage.stageWidth-(items[8].x+4))/items[8].videoWidth,
                       (stage.stageHeight-(items[8].y+4))/items[8].videoHeight);
      break;
    default: scale = .5; break;
    }
    transition();
  }
  public function pbFullScreen(event:MouseEvent):void {
    stage.displayState = (stage.displayState==StageDisplayState.FULL_SCREEN)?
      StageDisplayState.NORMAL:StageDisplayState.FULL_SCREEN;
    scale = (stage.displayState==StageDisplayState.FULL_SCREEN)?2:.5;
    pbScaleVideo(event);
  }
}

}
[SWF]

ダウンロード

サンプルコードの tarball … as-20080510.tar.gz

Copyright (C) 2008 Taiji Yamada, All rights reserved.