我们尝试在 Twilio 上播放流媒体音频,但只听到白噪声。音频是从 PlayHT 以 mulaw 格式接收的,但不确定我们做错了什么。
这是连接到我们的服务器应用程序的 Twilio 功能:
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
try {
//const connect = twiml.connect();
console.log("start");
const connect = twiml.connect();
connect.stream({
name: "PlayHT",
url: 'wss://f074-2a00-23a8-424f-b701-e862-5a32-4e45-397.ngrok-free.app'
});
console.log(twiml.toString());
callback(null, twiml);
} catch (error) {
console.error("Error connecting to WebSocket:", error);
callback(error);
}
};
这是服务器应用程序中的主要 websockets 功能:
wss.on('connection', function connection(ws) {
ws.on('message', async function incoming(message) {
// Parse the JSON string into an object
const messageObj = JSON.parse(message);
const event = messageObj.event;
if (event == 'start') {
console.log('received: %s', message);
const streamSid = messageObj.streamSid;
// Create a test text stream
const textStream = new Readable({
read() {
this.push('This is a test');
this.push(null); // End of data
},
});
// Stream audio from text
const stream = await PlayHTAPI.stream(textStream, {
voiceEngine: 'PlayHT2.0-turbo',
voiceId: process.env.PLAYHT_VOICE_ID,
output_format: "mulaw",
quality: 'low',
sample_rate: 8000
});
// Pipe the audio stream directly to the WebSocket
stream.on('data', (chunk) => {
console.log('sending: %s', chunk);
// Encode chunk in base64
const base64Chunk = chunk.toString('base64');
// Prepare the JSON object in Twilio's expected format
const twilioMessage = {
event: "media",
media: {
track: "outbound", // or "inbound" depending on your use case
payload: base64Chunk
},
streamSid: streamSid
};
// Send the JSON object as a string
ws.send(JSON.stringify(twilioMessage));
});
stream.on('end', () => {
const twilioMessage = {
event: "mark",
mark: {
"name": "PlayHT"
},
streamSid: streamSid
};
// Send the JSON object as a string
ws.send(JSON.stringify(twilioMessage));
console.log("--------------End stream--------------");
});
}
else {
if (event != 'media') {
console.log('received: %s', message);
}
}
});
});
日志看起来没问题,双方都没有错误。
谢谢你
我熟悉 Python SDK,而不是 JS,所以对此持保留态度,但一切看起来都不错。
我没有指定“出站”,但我怀疑这会导致您的错误。
您应该确保 twilio 确实正在连接,并且您能够传输 twilio 信号(检查“event”=“media”入站流)。
此外,您可以通过在本地保存并播放来轻松检查 play.ht 代码是否有效。我注意到您的 Play.ht 设置与我的有些差异,但这两个 SDK 相当不同。