This repository was archived by the owner on Feb 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReceiver.as
More file actions
87 lines (67 loc) · 2.26 KB
/
Receiver.as
File metadata and controls
87 lines (67 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package {
import flash.display.MovieClip;
import flash.events.*;
import flash.media.Sound;
import flash.net.Socket;
import flash.system.Security;
import flash.utils.ByteArray;
public class Receiver extends MovieClip{
public var socket:Socket;
private var bytes:ByteArray = new ByteArray();
private var output:Boolean = false;
var buffer:Vector.<Number> = new Vector.<Number>();
const BUFFER_SIZE:int = 2048; // output buffer size
const MIN_SAFETY_BUFFER:int = 1024; // minimum collected input before output starts
public function Receiver(){
socket = new Socket();
Security.allowDomain("*");
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(ProgressEvent.SOCKET_DATA, socketData);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.connect("localhost", 8080);
var sound:Sound = new Sound();
sound.addEventListener(SampleDataEvent.SAMPLE_DATA, soundSampleDataHandler);
sound.play();
}
public function socketData(event:ProgressEvent):void{
while(socket.bytesAvailable){
buffer.push(socket.readFloat());
}
trace(buffer.length);
if (!output && buffer.length >= MIN_SAFETY_BUFFER)
{
output = true;
}
}
public function soundSampleDataHandler(event:SampleDataEvent):void {
var outputBuffer:Vector.<Number>;
if (output){
if(buffer.length > BUFFER_SIZE){
outputBuffer = buffer.splice(0, BUFFER_SIZE);
}else{
outputBuffer = new Vector.<Number>(BUFFER_SIZE);
}
}else{
outputBuffer = new Vector.<Number>(BUFFER_SIZE);
}
var currentPhase:Number = 0;
var deltaPhase:Number = 440/44100;
for (var i:int=0; i<BUFFER_SIZE; i++){
if(outputBuffer[i] == 0){
currentPhase += deltaPhase;
var currentSample:Number = Math.sin(currentPhase*Math.PI*2);
}else{
var currentSample:Number = outputBuffer[i];
}
event.data.writeFloat(currentSample); // left channel
event.data.writeFloat(currentSample); // right channel
}
}
function onConnect(e:Event):void {
trace("Connected");
}
function onError(e:IOErrorEvent):void {
trace("IO Error: "+e);
}
}
}