| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- import { ref } from 'vue';
- export function useAudioPlayer() {
- let audioContext = null;
- let audioQueue = [];
- let isPlaying = false;
- // 初始化AudioContext
- const initAudioContext = () => {
- if (!audioContext) {
- audioContext = new (window.AudioContext || window.webkitAudioContext)({
- sampleRate: 24000 // 匹配TTS采样率
- });
- }
- };
- // 播放音频块
- const playAudioChunk = async (base64Audio) => {
- // console.log('playAudioChunk=========', base64Audio);
- initAudioContext();
- // 解码Base64音频数据
- const audioBytes = Uint8Array.from(atob(base64Audio), c => c.charCodeAt(0));
- audioQueue.push(audioBytes);
- if (!isPlaying) {
- processAudioQueue();
- }
- };
- // 处理音频队列
- const processAudioQueue = async () => {
- if (audioQueue.length === 0) {
- isPlaying = false;
- return;
- }
- isPlaying = true;
- const audioData = audioQueue.shift();
- try {
- const audioBuffer = await audioContext.decodeAudioData(audioData.buffer);
- const source = audioContext.createBufferSource();
- source.buffer = audioBuffer;
- source.connect(audioContext.destination);
- source.start(0);
- // 播放完成后继续处理队列
- source.onended = processAudioQueue;
- } catch (error) {
- console.error('音频解码失败:', error);
- isPlaying = false;
- }
- };
- // 停止播放并清理
- const stopPlayback = () => {
- if (audioContext) {
- audioContext.close().then(() => {
- audioContext = null;
- });
- }
- audioQueue = [];
- isPlaying = false;
- };
- return {
- playAudioChunk,
- stopPlayback
- };
- }
|