Discord Player
Intercepting streams

Intercepting Extractor Streams

Learn how to intercept the streams generated by extractors.

Intercepting Extractor Streams

This guide explains how to intercept the streams generated by extractors. This is helpful if you want to save or intercept streams before it is fed to the audio player. This can be done with the help of onStreamExtracted hook.

import { InterceptedStream, onStreamExtracted } from 'discord-player';
import { Readable } from 'node:stream';
 
onStreamExtracted(async (stream, queue) => {
  if (typeof stream === 'string') {
    // The stream is a URL
    return stream;
  }
 
  const isReadable = stream instanceof Readable;
  const readable = isReadable ? stream : stream.stream;
  const interceptor = new InterceptedStream();
 
  interceptor.interceptors.add(writable);
 
  if (isReadable) {
    // stream is already a readable stream
    return readable.pipe(interceptor);
  }
 
  // stream is ExtractorStreamable
  return {
    stream: readable.pipe(interceptor),
    $fmt: stream.$fmt,
  };
});

In the above example, we are intercepting the stream and adding a writable stream to it. This will allow you to intercept the stream and do whatever you want with it. You can also return a new stream or URL to replace the original stream.

On this page