twilio-media-stream-capture
v1.0.2
Published
Simple helper class for Node.js environment for saving Twilio Media Stream audio directly from Twilio to a local WAV format file.
Maintainers
Readme
A TypeScript/JavaScript library for saving Twilio Media Streams to WAV files in Node.js
This library provides a simple way to save Twilio media streams to local WAV files. It's written in TypeScript with full type definitions and works with both JavaScript and TypeScript projects.
Features
- 🎙️ Save Twilio Media Streams to WAV files
- 🚀 Written in TypeScript with full type definitions
- ⚡ Works with both JavaScript and TypeScript projects
- 📦 Zero dependencies (only Node.js built-in modules)
- ✅ Well-tested with Mocha
- 🔄 Supports both CommonJS and ES Modules
Installation
npm install twilio-media-stream-captureUsage
TypeScript / ES Modules
import TwilioMediaStreamSaveAudioFile from 'twilio-media-stream-capture';
const mediaStreamSaver = new TwilioMediaStreamSaveAudioFile({
saveLocation: __dirname,
saveFilename: 'my-twilio-media-stream-output',
onSaved: () => console.log('File was saved!'),
});
// Handle WebSocket messages from Twilio
wss.on('connection', (ws) => {
console.log('New connection initiated!');
ws.on('message', (message) => {
const msg = JSON.parse(message.toString());
switch (msg.event) {
case 'connected':
console.log('A new call has connected');
break;
case 'start':
console.log('Starting media stream...');
mediaStreamSaver.twilioStreamStart();
break;
case 'media':
mediaStreamSaver.twilioStreamMedia(msg.media.payload);
break;
case 'stop':
console.log('Call has ended');
mediaStreamSaver.twilioStreamStop();
break;
}
});
});JavaScript (CommonJS)
const TwilioMediaStreamSaveAudioFile = require('twilio-media-stream-capture');
const mediaStreamSaver = new TwilioMediaStreamSaveAudioFile({
saveLocation: __dirname,
saveFilename: 'my-twilio-media-stream-output',
onSaved: () => console.log('File was saved!'),
});
// ... rest of the code is the same as TypeScript exampleAPI Reference
new TwilioMediaStreamSaveAudioFile(options)
Creates a new instance of the media stream saver.
Options:
saveLocation(string): Directory where the audio file will be savedsaveFilename(string): Base filename (without extension) for the output fileonSaved(function, optional): Callback function that's called when the file is saved
Methods
twilioStreamStart()
Initializes the file stream and writes the WAV header. Call this when you receive the 'start' event from Twilio.
twilioStreamMedia(payload: string)
Writes media payload to the file. Call this when you receive the 'media' event from Twilio.
twilioStreamStop()
Finalizes the WAV file and closes the file stream. Call this when you receive the 'stop' event from Twilio.
Development
Prerequisites
- Node.js 14+
- npm or yarn
Building
# Install dependencies
npm install
# Build the project
npm run buildTesting
# Run tests
npm testLinting
# Run linter
npm run lintLicense
This project is UNLICENSED.
Acknowledgments
- Inspired by @tdeo's StackOverflow answer about saving μ-law audio streams from Twilio
console.log(
Starting media stream...); mediaStreamSaver.twilioStreamStart(); break; case "media": console.log("Receiving audio..."); mediaStreamSaver.twilioStreamMedia(msg.media.payload); break; case "stop": console.log("Call has ended"); mediaStreamSaver.twilioStreamStop(); break; default: break; } }); });
## Options
When you instantiate the library you can pass in the following options. They are not required and all optional.
- `saveLocation` - **(Optional)** Defaults to the local dir using `__dirname`. You can set any path you wish. Make sure path exists.
- `saveFilename` - **(Optional)** Defaults to the current date timestamp using `Date.now()`. You can set any filename you wish.
- `onSaved` - **(Optional)** This is a optional callback function that you can provide if you want to be notified when the audio wav file has been saved.
## Notes
- Inside the connected websocket `message` event make sure to call each of the corresponding methods for the incoming Twilio Media Stream message events:
### Twilio Media Stream Message Event: `start`
- ` mediaStreamSaver.twilioStreamStart()`
### Twilio Media Stream Message Event: `media`
- `mediaStreamSaver.twilioStreamMedia(twilioMediaPayload)`
### Twilio Media Stream Message Event: `stop`
- `mediaStreamSaver.twilioStreamStop()`
For getting started on how Twilio media streams work, check out [Twilio](https://www.twilio.com/media-streams).
## Author
👤 **Deep Chakraborty <[email protected]>**
* Website: https://stackoverflow.com/users/3761007/d-k
* Github: [@dk013](https://github.com/dk013)
***
_Made with ❤️ in Kolkata_
