Simple Sound Player: Accelerometer
forked from Simple Sound Player: Physical Button (diff: 42)
Related images
ActionScript3 source code
/**
* Copyright kotobuki ( http://wonderfl.net/user/kotobuki )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/gLbY
*/
// forked from kotobuki's Simple Sound Player: Physical Button
// forked from kotobuki's Simple Sound Player
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
import funnel.*;
import funnel.ui.*;
[SWF(backgroundColor="0x808080")]
public class SimpleSoundPlayer extends Sprite {
// これはMac OS Xの場合にはパーソナルウェブ共有、Windowsの場合には
// AN HTTPDなどを使用してローカルでサーバを用意することを想定した
// URLです。
private const URL_OF_SOUND_FILE:String = "http://localhost/sounds/snare.mp3";
private var _sound:Sound;
private var _gainer:Gainer;
private var _signalScope:SignalScope;
private var _isPlaying:Boolean = false;
private var _sensorPin:Pin;
public function SimpleSoundPlayer() {
_sound = new Sound();
_sound.addEventListener(Event.COMPLETE, onLoadComplete);
_sound.load(new URLRequest(URL_OF_SOUND_FILE));
_gainer = new Gainer();
_sensorPin = _gainer.analogInput(0);
// センサからの入力を確認するためのSignalScopeを用意します
_signalScope = new SignalScope(10, 10, 200, "Acceleration X");
addChild(_signalScope);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onLoadComplete(e:Event):void {
// サウンドの準備ができたらain 0に移動平均フィルタをセットし、
// 変化が起きた時に呼ぶイベントリスナをセットします
_sensorPin.addFilter(new Convolution(Convolution.MOVING_AVERAGE));
_sensorPin.addEventListener(PinEvent.CHANGE, onSensorChange);
}
private function onEnterFrame(e:Event):void {
// 毎フレームごとにSignalScopeを更新します
_signalScope.update(_sensorPin);
}
private function onSensorChange(e:PinEvent):void {
// フィルタをかける前の値とフィルタをかけた値の差が一定の値以上かどうかを判断します
if (_sensorPin.preFilterValue - _sensorPin.value > 0.3) {
// サウンドの再生中でなければ再生を開始します
if (!_isPlaying) {
var soundChannel:SoundChannel = _sound.play(30);
soundChannel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);
_isPlaying = true;
}
}
}
private function onSoundComplete(e:Event):void {
_isPlaying = false;
}
}
}
