File size: 4,125 Bytes
16a84ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import {
  LitElement,
  html,
} from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';

class AudioPlayer extends LitElement {
  static properties = {
    playEvent: {type: String},
    stopEvent: {type: String},
    enabled: {type: Boolean},
    data: {type: String},
  };

  constructor() {
    super();
    this.enabled = false;
    this.audioContext = null; // Initialize audio context
    this.sampleRate = 24000; // Gemini Live API sends data in 24000hz
    this.channels = 1;
    this.queue = [];
    this.isPlaying = false;

    this.onGeminiLiveStarted = (e) => {
      if (!this.enabled) {
        this.playAudio();
      }
    };

    this.onGeminiLiveStopped = (e) => {
      this.dispatchEvent(new MesopEvent(this.stopEvent, {}));
    };

    this.onAudioOutputReceived = (e) => {
      this.addToQueue(e.detail.data);
    };
  }

  connectedCallback() {
    super.connectedCallback();
    window.addEventListener(
      'audio-output-received',
      this.onAudioOutputReceived,
    );
    window.addEventListener(
      'gemini-live-api-started',
      this.onGeminiLiveStarted,
    );
    window.addEventListener(
      'gemini-live-api-stopped',
      this.onGeminiLiveStopped,
    );
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    if (this.audioContext) {
      this.audioContext.close();
    }
    window.removeEventListener(
      'audio-output-received',
      this.onAudioInputReceived,
    );
    window.removeEventListener(
      'gemini-live-api-started',
      this.onGeminiLiveStarted,
    );
    window.removeEventListener(
      'gemini-live-api-stopped',
      this.onGeminiLiveStopped,
    );
  }

  firstUpdated() {
    if (this.enabled) {
      this.playAudio();
    }
  }

  updated(changedProperties) {
    // Add audio chunks to queue to play.
    if (changedProperties.has('data') && this.data.length > 0) {
      this.addToQueue(this.data);
    }

    // Clear the queue if the audio player is disabled.
    if (changedProperties.has('enabled') && !this.enabled) {
      this.queue = [];
    }
  }

  addToQueue(base64Data) {
    if (!this.enabled) {
      return;
    }
    this.queue.push(base64Data);
    if (!this.isPlaying) {
      this.playNext();
    }
  }

  playAudio() {
    if (!this.enabled) {
      this.dispatchEvent(new MesopEvent(this.playEvent, {}));
    }
    if (!this.audioContext) {
      this.audioContext = new AudioContext();
    }
    this.playNext();
  }

  playNext() {
    if (!this.enabled || !this.audioContext || this.queue.length === 0) {
      this.isPlaying = false;
      return;
    }

    this.isPlaying = true;
    const data = this.queue.shift();
    const source = this.playPCM(data);

    source.onended = () => {
      this.playNext();
    };
  }

  playPCM(data) {
    // Convert base64 to binary.
    const binaryAudio = atob(data);

    // Convert binary string to ArrayBuffer.
    const audioBuffer = new ArrayBuffer(binaryAudio.length);
    const bufferView = new Uint8Array(audioBuffer);
    for (let i = 0; i < binaryAudio.length; i++) {
      bufferView[i] = binaryAudio.charCodeAt(i);
    }

    // Convert to 16-bit PCM data.
    const pcmData = new Int16Array(audioBuffer);

    // Create audio buffer.
    const frameCount = pcmData.length;
    const audioBufferData = this.audioContext.createBuffer(
      this.channels,
      frameCount,
      this.sampleRate,
    );

    // Get channel data and convert PCM to float32.
    const channelData = audioBufferData.getChannelData(0);
    for (let i = 0; i < frameCount; i++) {
      // Convert 16-bit PCM (-32768 to 32767) to float32 (-1.0 to 1.0)
      channelData[i] = pcmData[i] / 32768.0;
    }

    // Create and play the source.
    const source = this.audioContext.createBufferSource();
    source.buffer = audioBufferData;
    source.connect(this.audioContext.destination);
    source.start();

    return source;
  }

  render() {
    if (this.enabled) {
      return html`<span><slot></slot></span>`;
    }
    return html`<span @click="${this.playAudio}"><slot></slot></span>`;
  }
}

customElements.define('audio-player', AudioPlayer);