xterm
[VSoRC/.git] / node_modules / xterm / src / browser / services / SoundService.ts
1 /**
2  * Copyright (c) 2018 The xterm.js authors. All rights reserved.
3  * @license MIT
4  */
5
6 import { IOptionsService } from 'common/services/Services';
7 import { ISoundService } from 'browser/services/Services';
8
9 export class SoundService implements ISoundService {
10   serviceBrand: any;
11
12   private static _audioContext: AudioContext;
13
14   static get audioContext(): AudioContext | null {
15     if (!SoundService._audioContext) {
16       const audioContextCtor: typeof AudioContext = (<any>window).AudioContext || (<any>window).webkitAudioContext;
17       if (!audioContextCtor) {
18         console.warn('Web Audio API is not supported by this browser. Consider upgrading to the latest version');
19         return null;
20       }
21       SoundService._audioContext = new audioContextCtor();
22     }
23     return SoundService._audioContext;
24   }
25
26   constructor(
27     @IOptionsService private _optionsService: IOptionsService
28   ) {
29   }
30
31   public playBellSound(): void {
32     const ctx = SoundService.audioContext;
33     if (!ctx) {
34       return;
35     }
36     const bellAudioSource = ctx.createBufferSource();
37     ctx.decodeAudioData(this._base64ToArrayBuffer(this._removeMimeType(this._optionsService.options.bellSound)), (buffer) => {
38       bellAudioSource.buffer = buffer;
39       bellAudioSource.connect(ctx.destination);
40       bellAudioSource.start(0);
41     });
42   }
43
44   private _base64ToArrayBuffer(base64: string): ArrayBuffer {
45     const binaryString = window.atob(base64);
46     const len = binaryString.length;
47     const bytes = new Uint8Array(len);
48
49     for (let i = 0; i < len; i++) {
50       bytes[i] = binaryString.charCodeAt(i);
51     }
52
53     return bytes.buffer;
54   }
55
56   private _removeMimeType(dataURI: string): string {
57     // Split the input to get the mime-type and the data itself
58     const splitUri = dataURI.split(',');
59
60     // Return only the data
61     return splitUri[1];
62   }
63 }