PageRenderTime 10ms CodeModel.GetById 2ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/flash/flash-audio/src/com/ryanberdeen/audio/SampleSourcePlayer.as

http://echo-nest-remix.googlecode.com/
ActionScript | 67 lines | 50 code | 12 blank | 5 comment | 3 complexity | 76d97fa35a495e8839d0ea048d30660f MD5 | raw file
 1/*
 2 * Copyright 2009 Ryan Berdeen. All rights reserved.
 3 * Distributed under the terms of the MIT License.
 4 * See accompanying file LICENSE.txt
 5 */
 6
 7package com.ryanberdeen.audio {
 8  import flash.events.Event;
 9  import flash.events.EventDispatcher;
10  import flash.events.SampleDataEvent;
11  import flash.media.Sound;
12  import flash.media.SoundChannel;
13  import flash.utils.ByteArray;
14
15  public class SampleSourcePlayer extends EventDispatcher {
16    private static const SAMPLE_BUFFER_SIZE:int = 8192;
17    private var _sampleSource:ISampleSource;
18    private var outputSound:Sound;
19    private var soundChannel:SoundChannel;
20    private var playing:Boolean;
21
22    public function SampleSourcePlayer():void {
23      outputSound = new Sound();
24
25      outputSound.addEventListener(SampleDataEvent.SAMPLE_DATA, function(e:SampleDataEvent):void {
26        _sampleSource.extract(e.data, SAMPLE_BUFFER_SIZE);
27      });
28    }
29
30    public function set sampleSource(sampleSource:ISampleSource):void {
31      _sampleSource = sampleSource;
32    }
33
34    public function start():void {
35      if (soundChannel != null) {
36        soundChannel.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
37      }
38
39      soundChannel = outputSound.play();
40      soundChannel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
41      playing = true;
42    }
43
44    public function stop():void {
45      if (playing) {
46        soundChannel.stop();
47        playing = false;
48      }
49    }
50
51    public function get position():Number {
52      return Math.floor(soundChannel.position * 44.1);
53    }
54
55    public function get sourcePosition():Number {
56      return _sampleSource.toSourcePosition(position);
57    }
58
59    public function get sourceLength():Number {
60      return _sampleSource.length;
61    }
62
63    private function soundCompleteHandler(e:Event):void {
64      dispatchEvent(new Event(Event.SOUND_COMPLETE));
65    }
66  }
67}