'Study/Actionscript 3.0'에 해당되는 글 73건

  1. 2011.05.10 re: 동영상 링크 질문입니다 9
  2. 2011.04.13 window.open() (scrap) 6
  3. 2011.04.11 flash builder에서 작업올리기 4
  4. 2011.02.05 Line3D.addControlVertex [scrap] 1
  5. 2011.02.04 메모리관리
  6. 2011.02.02 Netstream error [ scrap ]
  7. 2011.02.02 Error #2148 (scrap)
  8. 2011.01.31 video controll as3.0 2
  9. 2011.01.15 Embed Vimeo Videos in Flash 1
  10. 2010.10.18 Adobe Flex 3 backup and export for web 3
Study/Actionscript 3.02011. 5. 10. 20:49
http://gametrailer.tistory.com/36

티스토리블로그를 추천드리고 싶지만.. 예전에는 외부트래픽용으로 티스토리 블로그를 많이 이용했습니다 스트리밍속도도 제일 빠르고. 단일파일 10Mb에 무제한 업로드이기때문에.. 하지만 요즘 티스토리에서 트래픽이 너무많이 발생하고 서버에도 자주 문제가 생기다보니 외부로 호출되는 트래픽관련 영상들은 이메일 통보 후 죄다 자르더라구요.
드랍박스(http://www.dropbox.com) 외국사이트인데 무료가입하면 2G의 용량을 줍니다. 간단한 가입절차를 거쳐 Public폴더에 영상을 올리면 스트리밍을 지원합니다. 외국사이트 특성상 스트리밍이 조금느립니다. 따로 jwplayer태그를 만들어주어야 재생이 가능합니다.
메가플러그(http://www.megaplug.net/) 유료사이트입니다. 무제한트래픽사이트이고 1G 1개월사용금액이 만원입니다.(부가세, 초기세팅비제외)용량별 기간별 구입이 가능합니다. 자체적으로 jwplayer태그를 제공하기 때문에 소스만 복사해서 가져오시면됩니다. 본인도 사용중인 서비스입니다.
미디어포스팅(http://www.mediaposting.co.kr) 단일파일 50Mb에 총용량은 무제한으로 쓸 수 있는 유료사이트입니다. 총용량과 트래픽은 무제한이고 1개월사용 금액이 만원(부가세제외)정도됩니다. 자체적으로 jwplayer태그를 제공하기 때문에 소스만 복사해서 가져오시면됩니다.
이글루스(http://egloos.com/) 이곳은 블로그 사이트인데.. 5Mb씩 업로드가 가능합니다. jwplayer태그를 만들어주어야 재생가능합니다.
쉐어팩토리(http://www.sharefactory.net) 아직 무료베타시험중인 사이트입니다. 3차베타진행중인데 3월15일까지라네요. 가입 후 24시간이내에 인증을 해주면 사용이 가능하고. 단일파일 80Mb에 총 10기가의 용량을 제공합니다. 자체적으로 jwplayer태그를 제공하기 때문에 소스만 복사해서 가져오시면됩니다.
제대로된 스트리밍 사이트를 이용하려면 유료서비스가 좋습니다.

flv나 mp4경우 플래시as3.0을 사용해서 불러와 재생시키는 방법이 있고 jwplayer(웹플레이어)로 재생시키는 방법이 있습니다.
jwplayer사용법은..

플래시사용법은 디시인사이드 플래시갤러리 공지에보면 자세히 나와있습니다. 
Posted by chacolina
Study/Actionscript 3.02011. 4. 13. 16:23

http://multimedia.kaywon.ac.kr:2009/2005_1/%C0%CE%C5%CD%B3%DD2/04%B0%AD/window_open.htm


팝업창을 만들어 주는 window.open() 메소드를 보겠습니다. window.open() 메소드의 사용법은 다음과 같습니다.

window.open("팝업창으로 보여줄 문서","팝업창의 이름","옵션")

  • <SCRIPT LANGUAGE="JavaScript">
  • <!--
  • window.open("http://www.dreamwiz.com", "dreamwiz", "width=500,height=300,left=0,top=0,resizable=no");
  • //-->
  • </SCRIPT>

이 예문은 http://www.dreamwiz.com 페이지를 가로 500픽셀, 높이 300 픽셀의 크기로 왼족위 모서리에 붙게 팝업창으로 열어줍니다. 두 번째 인자인 "dreamwiz" 는 뭐냐구요? 이 부분은 팝업창의 이름을 말하는 것으로 프레임 문서에서 타겟(target) 처럼 사용할 수 있습니다.. 즉, <a href="xxx.html" target="dreamwiz">열기</a> 처럼 사용하게 되면, 현재 드림위즈 홈페이지가 열려있는 팝업창에 xxx.html 문서가 열리게 되는 것이랍니다. 이 두 번째 인자에 아무것도 입력하지 않으려면 그냥 "" 만 표시 해 줍니다. (예) : window.open("http://www.dreamwiz.com", "", "옵션들")

세 번째 인자에는 옵션들을 설정 합니다. 이곳에서 사용할 수 있는 옵션에는 아래와 같은 것들이 있습니다

menubar

yes/no, 1/0

메뉴바를 보여주거나 숨깁니다

toolbar

yes/no, 1/0

도구막대를 보여주거나 숨깁니다

directories

yes/no, 1/0

디렉토리바를 보여주거나 숨깁니다

scrollbars

yes/no, 1/0

스크롤바를 보여주거나 숨깁니다

status

yes/no, 1/0

상태표시줄을 보여주거나 숨깁니다

location

yes/no, 1/0

주소표시줄을 보여주거나 숨깁니다

width

픽셀

팝업 윈도우의 가로크기를 지정합니다

height

픽셀

팝업 윈도우의 높이를 지정합니다

left

픽셀

팝업 윈도우의 x축 위치를 지정합니다

top

픽셀

팝업 윈도우의 y축 위치를 지정합니다

resizable

yes/no 1/0

팝업윈도우의 크기를 사용자가 임의로 수정할 수 있는지 여부를 지정합니다

fullscreen

 

전체화면 모드로 열어줍니다

channelmode

 

채널모드 창으로 열어줍니다

옵션인자를 지정하지 않으면 현재 창의 모양과 같은 형태로 팝업윈도우가 열리게 되고, 어느 한가지 옵션만 지정하면 나머지는 모두 디폴트 값으로 no 가 설정 됩니다.

버튼을 클릭하면 아무런 옵션이 없는 팝업 윈도우가 열리게 하는 코드는 아래와 같습니다

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2. <HTML>
  3. <HEAD>
  4. <META http-equiv="content-type" content="text/html; charset=euc-kr">
  5. <TITLE> Jasko Sample Script </TITLE>
  6.  
  7. <SCRIPT LANGUAGE="JavaScript">
  8. <!--
  9. function winOpen() {
  10. window.open("http://www.dreamwiz.com","dreamwiz");
  11. }
  12. //-->
  13. </SCRIPT>
  14.  
  15. </HEAD>
  16.  
  17. <BODY>
  18.  
  19. <input type=button onclick="winOpen();" value="옵션없이 팝업윈도우 열기">
  20.  
  21. </BODY>
  22.  
  23. </HTML>

위에서 보듯이 옵션을 사용하지 않으면 <a href="xxx.html" target="_blank">열기</a> 처럼 태그를 사용한 것과 같은 효과를 줍니다. 이 옵션 인자는 지정하지 않아도 되지만, 두 번재 인자인 name 은 사용하지 않더라도 반드시 "" 으로 표시해 주어야 한다는 것은 명심하기 바랍니다.

그럼, 이번에는 몇가지 옵션만 선별적으로 주는 예를 보겠습니다

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2. <HTML>
  3. <HEAD>
  4. <META http-equiv="content-type" content="text/html; charset=euc-kr">
  5. <TITLE> Jasko Sample Script </TITLE>
  6.  
  7. <SCRIPT LANGUAGE="JavaScript">
  8. <!--
  9. function winOpen() {
  10. window.open("http://www.dreamwiz.com","dreamwiz","location=yes,width=400,height=300");
  11. }
  12. //-->
  13. </SCRIPT>
  14.  
  15. </HEAD>
  16.  
  17. <BODY>
  18.  
  19. <input type=button onclick="winOpen();" value="location=yes,width=400,height=300">
  20.  
  21. </BODY>
  22.  
  23. </HTML>

위의 예에서 보듯이 특정 옵션을 지정하면 나머지 옵션값은 자동으로 no를 준 것과 같은 효과를 나타냅니다. 옵션을 줄때 주의할점은 절대 공백을 주어서는 안됩니다. 공백을 주게되면 네츠케이프 등에서는 에러를 발생시킬 수 있습니다

이번에는 잘 이용하면 아주 요긴하게 사용될 수 있는 fullscreen 모드와 channelmode 옵션으로 팝업윈도우를 열어보도록 하겠습니다

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2. <HTML>
  3. <HEAD>
  4. <META http-equiv="content-type" content="text/html; charset=euc-kr">
  5. <TITLE> Jasko Sample Script </TITLE>
  6.  
  7. <SCRIPT LANGUAGE="JavaScript">
  8. <!--
  9. function fullOpen() { // fullscreen 모드로 열기 함수
  10. window.open("http://www.dreamwiz.com","dreamwiz","fullscreen");
  11. }
  12.  
  13. function channelOpen() { // 채널모드로 열기 함수
  14. window.open("http://www.dreamwiz.com","dreamwiz","channelmode");
  15. }
  16. //-->
  17. </SCRIPT>
  18.  
  19. </HEAD>
  20.  
  21. <BODY>
  22.  
  23. <input type=button onclick="fullOpen();" value="fullscreen">
  24. <p>fullscreen 윈도우를 닫으려면 Alt+F4 키를 누르세요
  25. <p>
  26. <input type=button onclick="channelOpen();" value="channelmode">
  27.  
  28. </BODY>
  29.  
  30. </HTML>

 

Posted by chacolina
Study/Actionscript 3.02011. 4. 11. 20:52
http://fwangmeong.com/136




[첨부파일] :  


ant 를 통한 build 자동화 구축기 이다.

구축환경은 Flash Builder4 Burrito 이며 , 아마 Flash Builder 4 에서도 되지 싶다. ( Ant적용은 FB4 부터 되지 않았나 기억하기에.. )
지돌스타님의 포스팅을 기본으로 삽질을 했다. ( 참고 URL : http://blog.jidolstar.com/505 )
[ Action Script Project 를 생성한다.]

[ 첨부된 파일의 src 폴더와 build 폴더를 해당 프로젝트에 복사한다. ]
 

[ 첨부된 모습이다. ]

[ 간단하게 네모를 만든 소스. 컴파일 될 테스트 소스이다.]

[build] 폴더에 build.properties 파일을 연다.

[ 포커싱된 영역이 ftp 업로드될 설정 부분이다. 해당 부분에 ftp 접속 정보와 업로드될 path를 설정한다. ]


이제 가장 포인트가 될. ftp 업로드를 하기 위한 라이브러리를 등록한다.
[메뉴] - [Window] - [preferences] - [Ant] - [Runtime] 
에서 Classpath 탭매뉴에 Ant Home Entries 부분에 jar 파일을 등록한다. 
[ window - preferences 클릭 ]

[ 파일 첨부한 build 폴더에 libs 폴더에 commons-net-1.4.1.jar 파일을 라이브러리로 등록한다. FTP 업로드를 위한 라이브러리로 이해하면 되겠다.]

Ant를 편히 사용하기 위해  패널을 연다.
[ window - Show View - Other 클릭 ]

[ Ant 폴더에 Ant 패널 클릭 ]

Ant 패널에서 Ant를 통해 build 할 설정 파일을 불러온다.

[ Ant 패널에서 우클릭후 Add Buildfiles 클릭 ]


build.infomation.xml 파일은 지돌스타님 블로그에서 가져온 build.xml 파일이며 여러가지 설정이 담겨있다.
간단히 최소화 하여 , 컴파일 & ftp upload 만 남겨둔 파일이 build.xml 파일이다.
build.information.xml 파일은 참고만 하고 , build.xml 파일을 가지고 컴파일 및 업로드를 한다. 

[ build.xml 파일을 클릭하여 등록한다. ] 

[ 등록되어 올라온 모습 ]


현재 상태에서는 지돌스타님이 제공해 주신 샘플 파일이 그대로 적용되어진 상태이다.
즉 , 프로젝트가 생성되면서 생겨진 defulat 소스인 Main.as 파일은 적용이 안되고 , 파일을 첨부한 src 폴더안의 소스들만 적용 되어진 상태이다.
이제 Main.as 파일을 적용해보자.

build.xml 파일을 연다.


그림안의 설명을 보면 알수 있듯이 , 

<target name="compile all" depends="compile MyWidgets, compile widget1, compile widget2, compile widget3"/>
을 실행하면 depends 에 걸려 있는(?) 실행 커멘드 들이 같이 일괄적으로 실행된다.

2.번과 같이 아래와 같이 적용하여 XML 노드를 추가한후
<target name="compile MyApp" depends="mkdir bin">
     <mxmlc file="${src.dir}/Main.as" output="${bin.dir}/Main.swf" />
</target>


compile all 부분에  위 compile MyApp 을 추가하여 준다.
<target name="compile all" depends="compile MyWidgets, compile widget1, compile widget2, compile widget3, compile MyApp"/> 

ftp 부분의 노드는 build.properties 파일에 설정한 값을 토대로 업로드를 하는 일을 하므로 건드리지 않는다.

자. 이제 다 끝났다.
기존 첨부파일은 MyWidgets .as , Widgets1.as , Widgets2.as , Widgets3.as 파일을 가지고 각각 컴파일을 하여 bin 폴더에 해당 파일명.swf 파일로 컴파일이 된다.

여기서는 , 직접 우리가 컴파일 하고자 하는 Main.as 파일노드도 추가하고 , 전부 컴파일 되는 커멘드 노드부분에 해당 Main.as 파일 컴파일도 되도록 설정해 주었다.

ftp 업로드 부분에는 해당 폴더의 모든 *.swf 파일을 다 업로드 하므로 같이 업로드 된다.

Ant 를 실행하여 bin 폴더 안에 .swf 파일이 컴파일된 모습과 ftp 에 업로드 된 모습을 확인해 보겠다.

 

[ FTP 설정한 노드를 확인해 보면 알겠지만 , 전부 컴파일 한후 ftp에 업로드 한다. ]


[ Ant 실행전 폴더모습 ]

[ Ant 실행후 업로드 된 모습 ]

[ Ant 실행. Console 창을 보면 알수 있겠지만 5번의 컴파일과 ftp로 5 files sent 라는 문구를 확인할수 있다. 우측에 bin 폴더에 컴파일 되어진 모습도 볼수 있다.] 



Ant로  더 유용한 무언가를 할수 있는지는 추후 사용해 보면서 차차 업데이트 해 나가야 겠다.
우선적으로 여러 파일의 swf 산출물이 연결된 프로젝트에 웹 프로젝트로써 서버에 업로드를 해 주어야 하는 일괄적인 작업들을 Ant 란 놈으로 번거로움을 덜어 줄수 있도록 간단히 구축해 보았다.

끝.

 

 
Posted by chacolina
Study/Actionscript 3.02011. 2. 5. 04:35

package org.papervision3d.core.geom
{
	/**
	 * <p>
	 * The Lines object is a DisplayObject3D that is designed to contain and handle the rendering of
	 * Line3D objects. A Line3D is defined by two 3D vertices; one for each end. A line's start and end 
	 * vertices are converted into 2D space and rendered using the Flash drawing API lineTo method. 
	 * 
	 * Line3D can also render curves; add a control vertex using the Line3D.addControlVertex(...) method.
	 * The line's control vertex is then converted into 2D space and rendered using the Flash drawing API
	 * curveTo method.
	 * 
	 * The line's appearance is defined by its LineMaterial. 
	 * 
	 * </p>
	 * 
	 * <p>
	 * Example:
	 * </p>
	 * <pre><code>
	 * 
	 *  //This example creates a Lines3D DisplayObject3D and adds 100 lines into it. 
	 * 
	 *	var numLines : int = 100; 
	 *	
	 *	var lines3D : Lines3D = new Lines3D(); 
	 *	var lineMaterial : LineMaterial = new LineMaterial(0xff0000, 0.8); 
	 *	var lineWeight : Number = 5; 
	 *	
	 *	for(var i : int = 0; i<numLines; i++)
	 *	{
	 *		var startVertex : Vertex3D = new Vertex3D(Math.random()*200, Math.random()*200, Math.random()*200);
	 *		var endVertex 	: Vertex3D = new Vertex3D(Math.random()*200, Math.random()*200, Math.random()*200);
	 *		
	 *		var line : Line3D = new Line3D(lines3D, lineMaterial, lineWeight, startVertex, endVertex); 
	 *		
	 *		lines3D.addLine(line); 
	 *		
	 *	}
	 *	scene.addChild(lines3D); 
	 *		
 	 * </code></pre>
	 * </p>
	 * 
	 * <p>
	 * See also : LineMaterial
	 * </p>
	 * 
	 * @Author Ralph Hauwert
	 * @Author Seb Lee-Delisle
	 * @Author Alan Owen
 * 	 */
	 
	 
	 
	import org.papervision3d.core.geom.renderables.Line3D;
	import org.papervision3d.core.geom.renderables.Vertex3D;
	import org.papervision3d.core.log.PaperLogger;
	import org.papervision3d.core.render.command.RenderLine;
	import org.papervision3d.core.render.data.RenderSessionData;
	import org.papervision3d.core.render.draw.ILineDrawer;
	import org.papervision3d.materials.special.LineMaterial;
	import org.papervision3d.objects.DisplayObject3D;	

	public class Lines3D extends Vertices3D
	{
		
		public var lines:Array;
		private var _material:ILineDrawer;
		
		
		/**
		 * @param material			The default material for this Lines3D. If ommitted then the default
		 * 							LineMaterial3D is used. 
		 * @param name				An identifier for this Lines object. 
		 */
		 		 
		public function Lines3D(material:LineMaterial = null, name:String=null)
		{
			super(null, name);
			
			if(!material) this.material = new LineMaterial();
			else this.material = material;
			
			init();
		}
		
		private function init():void
		{
			this.lines = new Array();
		}
		
		/**
		* Converts 3D vertices into 2D space, to prepare for rendering onto the stage.
		*
		* @param 	parent				The parent DisplayObject3D
		* @param 	renderSessionData	The renderSessionData object for this render cycle. 
		 * 
		*/		
		public override function project( parent :DisplayObject3D, renderSessionData:RenderSessionData ):Number
		{
			// Vertices
			super.project( parent, renderSessionData );
			
			var line3D:Line3D;
			var screenZ:Number;
			var rc:RenderLine;
			
			for each(line3D in lines)
			{
				if(renderSessionData.viewPort.lineCuller.testLine(line3D))
				{
					rc = line3D.renderCommand;
					
					rc.renderer = line3D.material;
					rc.size = line3D.size;
					
					screenZ += rc.screenZ = (line3D.v0.vertex3DInstance.z + line3D.v1.vertex3DInstance.z)/2;
					
					rc.v0 = line3D.v0.vertex3DInstance;
					rc.v1 = line3D.v1.vertex3DInstance;
					
					renderSessionData.renderer.addToRenderList(rc);
				}
			}
			
			return screenZ/(lines.length+1);
		}
		
		
		/**
		 * Adds a Line3D object to this Lines3D container.  
		 * @param line 	The Line3D object to add. 
		 * 
		 */		
		public function addLine(line:Line3D):void
		{
			lines.push(line);
			line.instance = this;
			if(geometry.vertices.indexOf(line.v0) == -1)
			{
				geometry.vertices.push(line.v0);
			}
			
			if(geometry.vertices.indexOf(line.v1) == -1)
			{
				geometry.vertices.push(line.v1);
			}
			
			if(line.cV){
				if(geometry.vertices.indexOf(line.cV) == -1)
				{
					geometry.vertices.push(line.cV);
				}
				
			}
		}
		
		/**
		 * Creates a new line from the parameters passed and adds it.  
		 * @param size		The weight of the line. 
		 * @param x0		The line's start x position. 
		 * @param y0		The line's start y position. 
		 * @param z0		The line's start z position. 
		 * @param x1		The line's end x position. 
		 * @param y1		The line's end y position. 
		 * @param z1		The line's end z position. 
		 * @return 			The line just created. 
		 * 
		 */		
		public function addNewLine(size:Number, x0:Number, y0:Number, z0:Number, x1:Number, y1:Number, z1:Number) : Line3D
		{
			var line:Line3D = new Line3D(this, material as LineMaterial, size, new Vertex3D(x0,y0,z0), new Vertex3D(x1,y1,z1));
			addLine(line);
			
			return line; 
		
		}
		
		/**
		 * This is identical to addNewLine, except it breaks up the line into several shorter line segments
		 * that together make up the full line. This would be useful for improved z-depth sorting. 
		 * 
		 * @param size		The weight of the line. 
		 * @param segments	The number of segments to break up the line into
		 * @param x0		The line's start x position. 
		 * @param y0		The line's start y position. 
		 * @param z0		The line's start z position. 
		 * @param x1		The line's end x position. 
		 * @param y1		The line's end y position. 
		 * @param z1		The line's end z position. 
		 * @return 			An array of the lines just created. 
		 * 
		 */		
		public function addNewSegmentedLine(size:Number, segments:Number, x0:Number, y0:Number, z0:Number, x1:Number, y1:Number, z1:Number) : Array
		{
			//Do line interpolation, and add a bunch of segments for it.
			var xStep:Number = (x1-x0)/segments;
			var yStep:Number = (y1-y0)/segments;
			var zStep:Number = (z1-z0)/segments;
			
			var newLines : Array = new Array; 
			
			var line:Line3D;
			var pv:Vertex3D = new Vertex3D(x0,y0,z0);
			var nv:Vertex3D;
			for(var n:Number = 0; n<=segments; n++){
				nv = new Vertex3D(x0 + xStep*n, y0+yStep*n, z0+zStep*n);
				line = new Line3D(this, material as LineMaterial, size, pv, nv);
				addLine(line);
				newLines.push(line); 
				pv = nv;
			}
		
			return newLines; 
		}
		
		/**
		 * Removes a line. 
		 * @param line 	The line to remove. 
		 * 
		 */		
		public function removeLine(line:Line3D) : void
		{
			var lineindex : int = lines.indexOf(line);
			if(lineindex>-1) 
			{
				lines.splice(lineindex,1);	
			}
			else
			{
				PaperLogger.warning("Papervision3D Lines3D.removeLine : WARNING removal of non-existant line attempted. ");
			}
		}
		/**
		 * Removes all the lines.  
		 * 
		 */		
		public function removeAllLines():void
		{
			while ( lines.length > 0 )
			{
				removeLine( lines[0] ) ;
			} 		
			
		}
		
		
	}
}
Posted by chacolina
Study/Actionscript 3.02011. 2. 4. 22:25
Posted by chacolina
Study/Actionscript 3.02011. 2. 2. 18:33
Posted by chacolina
Study/Actionscript 3.02011. 2. 2. 16:33

http://www.cyworld.com/qkrals01/3323288



Error #2148

박민수2010-01-06 12:19:21주소복사
조회 286  스크랩 0
2007/03/07 09:42

폴더를 옮겨서 실행시키시는거죠?
보안상 이유로 Flex Builder 의 Flex Project 디렉토리 외부에서 로컬파일 접근은 안됩니다.

c:\Documents and Settings\Administrator\Application Data\Macromedia\Flash Player\#Security\FlashPlayerTrust\
가 flash player 가 접근할 수 있는 디렉토리 들이 기록되있는 곳일 거구요.
Flex Builder 는 Flex Project 의 workspace 디렉토리를 저 파일에 자동으로 기록해 놓습니다.

 

 

2008/05/07 10:20

플렉스에서 다음과 같이 xml 파일을 읽어 들이지 못하는 이유는 보안 박스 와 관련된

오류 입니다.

이러한 오류를 수정하기 위해서는 다음과 같이 하면 됩니다.



SecurityError: Error #2148: SWF file file:///C:/Documents and Settings/UserProfile/Desktop/flexstore/bin-release/flexstore.swf cannot access local resource myFile.swf. Only local-with-filesystem and trusted local SWF files may access local resources. 





플렉스 메뉴에서 

Project > Properties > Flex Complier 를 선택합니다.



Additional complier Arguments 에서

local 이라는 메뉴를 지우고 



-use-network=false



라고 넣어줍니다.

 

 

Posted by chacolina
Study/Actionscript 3.02011. 1. 31. 20:32
http://livedocs.adobe.com/flex/3/html/help.html?content=Working_with_Video_32.html



Video
With ActionScript 3 
Author: Meir Ohayon     
       ohmeir@gmail.com
Based on official documuntation of Adobe Meir Ohayon :   ohmeir@gmail.com        
1
Alternatives 
VideoDisplay Control 
Creating FLV in FLASH CS3 Professional and selecting 
the option of skin for your video including common 
playback controls. 
Working with videos : Classes 
Video Class – Display Object 
o The actual video content box on the Stage is an instance of 
the Video class. 
NetStream Class – Represent stream of video data . 
NetConnection Class – Represent connection handling to 
stream source. 
Important concepts and terms 
Cue point – A marker placed on specific moment 
(bookmarking). 
Encoding – Converting to another video data format. 
Frame 
Keyframe – A video frame which contains the full 
information for the frame. Other frames that follow a 
keyframe only contain information about how they differ 
from the keyframe. 
Metadata Meir Ohayon :   ohmeir@gmail.com        
2
Progressive Download 
Loading in sequence 
o You can't jump ahead to a part of the video that hasn't 
loaded. 
True Streaming (Aka Streaming) 
Loading chanks from the video file by demand. 
o Needs implemantation of special protocol to split video data 
into fragments on the server → RTMP
o Needs server that can handle remote procrdure calls for 
getting demands (RPC) 
o Needs persistant connection to server (getting demands + 
handling RTMP)
Flash Media Server enables all that. Meir Ohayon :   ohmeir@gmail.com        
3
Setting connection 
Connecting to local: 
var nc:NetConnection = new NetConnection(); 
nc.connect(null);
Connecting to Flash Media Server: 
var nc:NetConnection = new NetConnection(); 
nc.connect("rtmp://localhost/HelloWorld");
Setting stream and playing it 
var ns:NetStream = new NetStream(nc); 
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, 
asyncErrorHandler); 
ns.play("video.flv"); 
function asyncErrorHandler(event:AsyncErrorEvent):void { 
  // ignore error 
 {
Handling display 
var vid:Video = new Video(); 
vid.attachNetStream(ns); 
addChild(vid); Meir Ohayon :   ohmeir@gmail.com        
4
NetStream methods 
pause( )  
o If the video is already paused does nothing. 
resume( ) 
o Resumes paused video. 
o If the video is already playing does nothing. 
seek( ) 
o Seeks the keyframe closest to the specified location (an 
offset, in seconds, from the begining of the stream). 
togglePause( ) 
o Pauses\Resumes playback of stream. 
Notes on NetStream methods 
There is no stop( ) method. 
o In order to stop a stream you must pause playback and seek 
to the begining of the stream. 
The play( ) method doesn't resume playback, it is used for 
loading video files.Meir Ohayon :   ohmeir@gmail.com        
5
NetStream methods: Example 
var nc:NetConnection = new NetConnection(); 
nc.connect(null);  
var ns:NetStream = new NetStream(nc); 
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, 
asynErrHandler);  
ns.play("video.flv");  
function asynErrHandler(e:AsyncErrorEvent):void { 
// ignore error  
  {
var vid:Video = new Video(); 
vid.attachNetStream(ns);  
addChild(vid); 
pauseBtn.addEventListener(MouseEvent.CLICK, 
pauseHandler); 
playBtn.addEventListener(MouseEvent.CLICK, playHandler); 
stopBtn.addEventListener(MouseEvent.CLICK, stopHandler); 
togglePauseBtn.addEventListener(MouseEvent.CLICK, 
togPauseHandler);  
function pauseHandler(event:MouseEvent):void { 
ns.pause();  
  {
function playHandler(event:MouseEvent):void { 
ns.resume();  
  {
function stopHandler(event:MouseEvent):void {  
// Pause the stream and move the playhead back to // the 
beginning of the stream.  
ns.pause();  
ns.seek(0);  
  {
function togPauseHandler(event:MouseEvent):void { 
ns.togglePause();  
  {Meir Ohayon :   ohmeir@gmail.com        
6
This way you can implement a 
playlist that loads the next 
video once the current video 
has finished playing. 
Detecting the end of a video stream 
ns.addEventListener(NetStatusEvent.NET_STATUS, 
statusHandler);  
function statusHandler(event:NetStatusEvent):void 
  }
trace(event.info.code);  
  {
Output: 
NetStream.Play.Start  
NetStream.Buffer.Empty  
NetStream.Buffer.Full  
NetStream.Buffer.Empty  
NetStream.Buffer.Full  
NetStream.Buffer.Empty  
NetStream.Buffer.Full  
NetStream.Buffer.Flush  
NetStream.Play.Stop  
NetStream.Buffer.Empty  
NetStream.Buffer.Flush  
Reminder 
var nc:NetConnection = new NetConnection(); 
nc.connect(null); 
var ns:NetStream = new NetStream(nc); 
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, 
asyncErrorHandler); 
ns.play("video.flv"); 
function asyncErrorHandler(event:AsyncErrorEvent):void { 
    trace(event.text); 
 {
var vid:Video = new Video(); 
vid.attachNetStream(ns); 
addChild(vid); Meir Ohayon :   ohmeir@gmail.com        
7
Problem with the reminder when having metadata or 
cue point(s) 
Error #2095: flash.net.NetStream was unable to invoke callback 
onMetaData. 
Error #2095: flash.net.NetStream was unable to invoke callback 
onCuePoint. 
Error #2095: flash.net.NetStream was unable to invoke callback 
onCuePoint. 
Error #2095: flash.net.NetStream was unable to invoke callback 
onCuePoint. 
The error occurs because the NetStream object was unable to 
find an onMetaData or onCuePoint callback method. 
Solution 1: Set the NetStream object's client 
property to an Object 
var nc:NetConnection = new NetConnection(); 
nc.connect(null); 
var customClient:Object = new Object(); 
var ns:NetStream = new NetStream(nc); 
ns.client = customClient; 
ns.play("video.flv"); 
var vid:Video = new Video(); 
vid.attachNetStream(ns); 
addChild(vid); 
If you wanted to listen for either the onMetaData or onCuePoint
callback methods, you would need to define methods to handle those 
callback methods, as shown in the following snippet: 
var customClient:Object = new Object(); 
customClient.onMetaData = metaDataHandler; 
function metaDataHandler(infoObject:Object):void 
 }
    trace("metadata"); 
 {Meir Ohayon :   ohmeir@gmail.com        
8
Solution 2: Create a custom class and define 
methods to handle the callback methods 
var nc:NetConnection = new NetConnection(); 
nc.connect(null); 
var ns:NetStream = new NetStream(nc); 
ns.client = new CustomClient(); 
ns.play("video.flv"); 
var vid:Video = new Video(); 
vid.attachNetStream(ns); 
addChild(vid); 
The CustomClient class is as follows: 
package 
 }
    public class CustomClient 
 }    
        public function onMetaData(infoObject:Object):void 
 }        
            trace("metadata"); 
 {        
 {    
 {
Solution 3: Extend the NetStream class and add 
methods to handle the callback methods 
var ns:CustomNetStream = new CustomNetStream(); 
ns.play("video.flv"); 
var vid:Video = new Video(); 
vid.attachNetStream(ns); 
addChild(vid); 
The following code listing defines the CustomNetStream class that 
extends the NetStream class, handles the creation of the necessary 
NetConnection object, and handles the onMetaData and onCuePoint
callback handler methods: Meir Ohayon :   ohmeir@gmail.com        
9
package 
 }
    import flash.net.NetConnection; 
    import flash.net.NetStream; 
    public class CustomNetStream extends NetStream 
 }    
        private var nc:NetConnection; 
        public function CustomNetStream() 
 }        
            nc = new NetConnection(); 
            nc.connect(null); 
            super(nc); 
 {        
        public function onMetaData(infoObject:Object):void 
 }        
            trace("metadata"); 
 {        
        public function onCuePoint(infoObject:Object):void 
 }        
            trace("cue point"); 
 {        
 {    
 {
If you want to rename the onMetaData() and onCuePoint() methods 
in the CustomNetStream class, you could use the following code: 
package 
 }
    import flash.net.NetConnection; 
    import flash.net.NetStream; 
    public class CustomNetStream extends NetStream 
 }    
        private var nc:NetConnection; 
        public var onMetaData:Function; 
        public var onCuePoint:Function; 
        public function CustomNetStream() 
 }        
            onMetaData = metaDataHandler; 
            onCuePoint = cuePointHandler; 
            nc = new NetConnection(); 
            nc.connect(null); 
            super(nc); 
 {        Meir Ohayon :   ohmeir@gmail.com        
10
        private function metaDataHandler(infoObject:Object):void 
 }        
            trace("metadata"); 
 {        
        private function cuePointHandler(infoObject:Object):void 
 }        
            trace("cue point"); 
 {        
 {    
 {
Solution 4: Extend the NetStream class and make it 
dynamic 
var ns:DynamicCustomNetStream = new DynamicCustomNetStream(); 
ns.play("video.flv"); 
var vid:Video = new Video(); 
vid.attachNetStream(ns); 
addChild(vid); 
The DynamicCustomNetStream class is as follows: 
package 
 }
    import flash.net.NetConnection; 
    import flash.net.NetStream; 
    public dynamic class DynamicCustomNetStream extends NetStream 
 }    
        private var nc:NetConnection; 
        public function DynamicCustomNetStream() 
 }        
            nc = new NetConnection(); 
            nc.connect(null); 
            super(nc); 
 {        
 {    
 {
Even with no handlers for the onMetaData and onCuePoint callback 
handlers, no errors are thrown since the DynamicCustomNetStream class Meir Ohayon :   ohmeir@gmail.com        
11
is dynamic. If you want to define methods for the onMetaData and 
onCuePoint callback handlers, you could use the following code: 
var ns:DynamicCustomNetStream = new DynamicCustomNetStream(); 
ns.onMetaData = metaDataHandler; 
ns.onCuePoint = cuePointHandler; 
ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv"); 
var vid:Video = new Video(); 
vid.attachNetStream(ns); 
addChild(vid); 
function metaDataHandler(infoObject:Object):void 
 }
    trace("metadata"); 
 {
function cuePointHandler(infoObject:Object):void 
 }
    trace("cue point"); 
 {
Solution 5: Set the NetStream object's client 
property to this 
By setting the client property to this, Flash Player looks in the 
current scope for onMetaData() and onCuePoint() methods. You 
can see this in the following example: 
var nc:NetConnection = new NetConnection(); 
nc.connect(null); 
var ns:NetStream = new NetStream(nc); 
ns.client = this; 
ns.play("video.flv"); 
var vid:Video = new Video(); 
vid.attachNetStream(ns); 
addChild(vid); Meir Ohayon :   ohmeir@gmail.com        
12
If the onMetaData or onCuePoint callback handlers are called and 
no methods exist to handle the callback, no errors are generated. To 
handle these callback handlers, create an onMetaData() and 
onCuePoint() method in your code, as seen in the following snippet: 
function onMetaData(infoObject:Object):void 
 }
    trace("metadata"); 
 {
function onCuePoint(infoObject:Object):void 
 }
    trace("cue point"); 
 {
Setting the buffer time 
ns.bufferTime(8); 
The default time is 10 (mesured in seconds). Meir Ohayon :   ohmeir@gmail.com        
13
Using video metadata 
The previous code generates code similar to the following, assuming your 
FLV file contains cue points and audio: 
width: 320 
audiodelay: 0.038 
canSeekToEnd: true 
height: 213 
cuePoints: ,, 
audiodatarate: 96 
duration: 16.334 
videodatarate: 400 
framerate: 15 
videocodecid: 4 
audiocodecid: 2 
var nc:NetConnection = new NetConnection(); 
nc.connect(null); 
var ns:NetStream = new NetStream(nc); 
ns.client = this; 
ns.play("video.flv"); 
var vid:Video = new Video(); 
vid.attachNetStream(ns); 
addChild(vid); 
function onMetaData(infoObject:Object):void 
 }
    var key:String; 
    for (key in infoObject) 
 }    
        trace(key + ": " + infoObject[key]);
 {    
 {Meir Ohayon :   ohmeir@gmail.com        
14
Video metadata: videocodecid 
videocodecid  Codec name 
2 Sorenson H.263 
3 Screen video (SWF 7 and later only) 
4 VP6 (SWF 8 and later only) 
5 VP6 video with alpha channel (SWF 8 and later only) 
Video metadata: audiocodecid 
audiocodecid  Codec Name 
0 uncompressed 
1 ADPCM 
2 mp3 
5 Nellymoser 8kHz mono 
6 Nellymoser 
Video: Complete Example 
Download and extract from 
www.adobe.com/go/as3examples
In the folder Samples/VideoJukebox 
add those files to new flex project: 
o videoJukebox.mxml 
o playlist.xml
Posted by chacolina
Study/Actionscript 3.02011. 1. 15. 16:30







Posted by chacolina
Study/Actionscript 3.02010. 10. 18. 12:00
Posted by chacolina