/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. package com.ryanberdeen.audio {
  7. import flash.events.Event;
  8. import flash.events.EventDispatcher;
  9. import flash.events.SampleDataEvent;
  10. import flash.media.Sound;
  11. import flash.media.SoundChannel;
  12. import flash.utils.ByteArray;
  13. public class SampleSourcePlayer extends EventDispatcher {
  14. private static const SAMPLE_BUFFER_SIZE:int = 8192;
  15. private var _sampleSource:ISampleSource;
  16. private var outputSound:Sound;
  17. private var soundChannel:SoundChannel;
  18. private var playing:Boolean;
  19. public function SampleSourcePlayer():void {
  20. outputSound = new Sound();
  21. outputSound.addEventListener(SampleDataEvent.SAMPLE_DATA, function(e:SampleDataEvent):void {
  22. _sampleSource.extract(e.data, SAMPLE_BUFFER_SIZE);
  23. });
  24. }
  25. public function set sampleSource(sampleSource:ISampleSource):void {
  26. _sampleSource = sampleSource;
  27. }
  28. public function start():void {
  29. if (soundChannel != null) {
  30. soundChannel.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
  31. }
  32. soundChannel = outputSound.play();
  33. soundChannel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
  34. playing = true;
  35. }
  36. public function stop():void {
  37. if (playing) {
  38. soundChannel.stop();
  39. playing = false;
  40. }
  41. }
  42. public function get position():Number {
  43. return Math.floor(soundChannel.position * 44.1);
  44. }
  45. public function get sourcePosition():Number {
  46. return _sampleSource.toSourcePosition(position);
  47. }
  48. public function get sourceLength():Number {
  49. return _sampleSource.length;
  50. }
  51. private function soundCompleteHandler(e:Event):void {
  52. dispatchEvent(new Event(Event.SOUND_COMPLETE));
  53. }
  54. }
  55. }