audio.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. namespace audio {
  2. export class AudioManager {
  3. context: AudioContext;
  4. volume: GainNode;
  5. output: AudioNode;
  6. constructor() {
  7. this.context = new AudioContext();
  8. this.volume = this.context.createGain();
  9. this.volume.connect(this.context.destination);
  10. this.output = this.volume;
  11. }
  12. getTime(): number {
  13. return this.context.currentTime;
  14. }
  15. loadTrack(url: string): Promise<Track> {
  16. return window.fetch(url)
  17. .then(response => response.arrayBuffer())
  18. .then(buffer => this.context.decodeAudioData(buffer))
  19. .then(audioBuffer => new Track(this, audioBuffer))
  20. }
  21. }
  22. export class Track {
  23. manager: AudioManager;
  24. buffer: AudioBuffer;
  25. source: AudioBufferSourceNode | null;
  26. playStartTime: number;
  27. hasStarted: boolean;
  28. isFinished: boolean;
  29. constructor(manager: AudioManager, buffer: AudioBuffer) {
  30. this.manager = manager;
  31. this.buffer = buffer;
  32. this.playStartTime = 0;
  33. this.hasStarted = false;
  34. this.isFinished = false;
  35. }
  36. play(): void {
  37. this.source = this.manager.context.createBufferSource();
  38. this.source.buffer = this.buffer;
  39. this.source.connect(this.manager.output);
  40. this.source.onended = () => {
  41. this.isFinished = true;
  42. }
  43. this.isFinished = false;
  44. this.hasStarted = true;
  45. this.playStartTime = this.manager.getTime();
  46. this.source.start();
  47. }
  48. stop(): void {
  49. this.isFinished = true;
  50. if (this.source) {
  51. this.source.stop();
  52. }
  53. }
  54. getTime(): number {
  55. if (this.isFinished) {
  56. return this.getDuration();
  57. } else if (!this.hasStarted) {
  58. return 0;
  59. } else {
  60. return this.manager.getTime() - this.playStartTime;
  61. }
  62. }
  63. getDuration(): number {
  64. return this.buffer.duration;
  65. }
  66. }
  67. }