2 * Copyright (c) 2018 The xterm.js authors. All rights reserved.
6 import { IOptionsService } from 'common/services/Services';
7 import { ISoundService } from 'browser/services/Services';
9 export class SoundService implements ISoundService {
12 private static _audioContext: AudioContext;
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');
21 SoundService._audioContext = new audioContextCtor();
23 return SoundService._audioContext;
27 @IOptionsService private _optionsService: IOptionsService
31 public playBellSound(): void {
32 const ctx = SoundService.audioContext;
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);
44 private _base64ToArrayBuffer(base64: string): ArrayBuffer {
45 const binaryString = window.atob(base64);
46 const len = binaryString.length;
47 const bytes = new Uint8Array(len);
49 for (let i = 0; i < len; i++) {
50 bytes[i] = binaryString.charCodeAt(i);
56 private _removeMimeType(dataURI: string): string {
57 // Split the input to get the mime-type and the data itself
58 const splitUri = dataURI.split(',');
60 // Return only the data