import { AliRtcPlugin, LocalStreamInfo } from 'aliyun-rtc-sdk';
export default class UserNamePlugin extends AliRtcPlugin {
private canvas: HTMLCanvasElement;
private requestId?: number;
// text は描画したいユーザー名を指定します。
constructor(text: string) {
super('UserNamePlugin'); // プラグインのカスタム名。グローバルに一意である必要があります。
this.options = { text };
this.canvas = document.createElement('canvas');
}
isSupported(): boolean {
// プラグインは、特定のバージョンの aliyun-rtc-sdk の機能に依存する必要はありません。したがって、値を true に設定します。
return true;
}
setOptions(options: { text: string }): void {
// 描画したいユーザー名を動的に更新するかどうかを指定します。
this.options = options;
}
shouldUpdate(): boolean {
// カメラのオン/オフなど、ストリームの状態が変化したときに process メソッドを呼び出すかどうかを指定します。この例では、値を true に設定します。
return true;
}
process(streamInfo: LocalStreamInfo): Promise<void> {
if (streamInfo.currentVideoTrack) {
// ビデオトラックが存在する場合、ビデオトラックの処理方法を定義します。
const videoTrack = streamInfo.currentVideoTrack as MediaStreamVideoTrack;
const settings = videoTrack.getSettings();
// キャンバスの幅と高さをビデオストリームと同じになるように調整します。
this.canvas.width = settings.width!;
this.canvas.height = settings.height!;
// MediaStreamTrack オブジェクトを video 要素のソースに変換します。
const stream = new MediaStream([videoTrack]);
const videoElement = document.createElement('video');
videoElement.srcObject = stream;
videoElement.play();
const ctx = this.canvas.getContext('2d')!;
// ビデオフレームを一定の間隔でキャンバスに描画し、テキストを追加します。
const drawFrame = () => {
if (videoElement.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
ctx.drawImage(videoElement, 0, 0, this.canvas.width, this.canvas.height);
// 右下隅にテキストを追加します。
ctx.fillStyle = 'white'; // テキストの色。
ctx.font = '40px Arial'; // テキストのサイズとフォント。
ctx.textAlign = 'right'; // テキストの配置方向。
ctx.fillText(this.options.text, this.canvas.width - 20, this.canvas.height - 20); // テキストの位置。
}
this.requestId = requestAnimationFrame(drawFrame); // フレームを連続して描画します。
}
this.requestId = requestAnimationFrame(drawFrame);
// 新しい MediaStream オブジェクトを作成します。
const newStream = this.canvas.captureStream(settings.frameRate); // 必要に応じて、ビジネス要件に基づいて別のフレームレートを指定することもできます。
const newVideoTrack = newStream.getVideoTracks()[0];
// streamInfo.updateVideoTrack を呼び出して、ビデオトラックを置き換えます。
streamInfo.updateVideoTrack(newVideoTrack);
} else if (this.requestId) {
// requestAnimationFrame が設定されていて、ビデオトラックが存在しない場合は、描画をキャンセルします。
cancelAnimationFrame(this.requestId);
}
return Promise.resolve();
}
}