import os
import base64
import json
import asyncio
from websockets import connect
async def send_audio_chunks(websocket, audio_folder_path, bot_id):
try:
# Get all files in the folder
files = os.listdir(audio_folder_path)
for file in files:
with open(os.path.join(audio_folder_path, file), 'rb') as pcm_file:
while True:
chunk = pcm_file.read(64000)
if not chunk: # End of file
break
base64_audio = base64.b64encode(chunk).decode('utf-8')
await websocket.send_text(json.dumps({
"command": "sendaudio",
"audiochunk": base64_audio
}))
print(f"[Audio chunk sent] {len(base64_audio)}")
print("sending audio")
print(f"[Audio sent] to {bot_id}")
except Exception as e:
print(f"[Audio error] {bot_id}: {e}")
# Usage example
async def main():
async with connect("wss://your-websocket-server.com") as websocket:
# Wait for ready event
ready_event = await websocket.recv()
ready_data = json.loads(ready_event)
bot_id = ready_data["bot_id"]
# Send a message
await websocket.send_text(json.dumps({
"command": "sendmsg",
"message": "Hello from server!",
"bot_id": bot_id
}))
# Send audio chunks
await send_audio_chunks(websocket, "/path/to/audio/folder", bot_id)
# Run the example
asyncio.run(main())