kaaaxcreators
kaaaxcreators

Reputation: 133

Convert internal.Writable to NodeJS.WritableStream

I want to output sound to my speaker using ytdl-core and fluent-ffmpeg

I get the sound from yt and use ffmpeg to convert it to pcm and now i want to pipe it to my speaker

speaker uses internal.Writable

naudiodon uses NodeJS.WritableStream

when piping to speaker everything works

when piping to naudiodon I get a typescript error and hear nothing

What is the difference between the two streams and can I convert them, because I need to use naudiodon because there I can specify my output device

Edit:

WritableStream is a Web API and internal.Writable is from Node.js

Can I convert a Writable to a WritableStream?

Github Issue

Upvotes: 1

Views: 451

Answers (1)

shtse8
shtse8

Reputation: 1365

You need to create a WritableStream to apply actions to underlying Writable. Here is an example.

function toWebWritable<T extends Uint8Array>(writable: Writable): WritableStream<T> {
    return new WritableStream<T>({
        write(chunk, controller) {
            return new Promise((resolve, reject) => {
                console.log('Writing chunk:', chunk.length);
                const result = writable.write(Buffer.from(chunk), (error) => {
                    console.log('Write result:', result, error, chunk.length);
                    if (error) {
                        controller.error(error);
                        reject(error);
                    }
                });
                if (!result) {
                    writable.once('drain', resolve);
                } else {
                    resolve();
                }
            });
        },
        close() {
            // Assuming a graceful closure is desired:
            return new Promise((resolve) => {
                writable.end(resolve);
                // If there's an error, it should be handled by listening to the 'error' event on the writable itself.
            });
        },
        abort(reason) {
            writable.destroy(asError(reason));
        }
    });
}

Upvotes: 0

Related Questions