zoukankan      html  css  js  c++  java
  • js 使用socket-io发送文件

    前端

    import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
    import { MediaDevicesService } from '../../media-devices.service';
    import * as io from 'socket.io-client';
    import { MESSAGE_EVENT } from '@live-video-example/p2p';
    
    @Component({
      selector: 'live-video-example-get-audio',
      templateUrl: './get-audio.component.html',
      styleUrls: ['./get-audio.component.styl'],
    })
    export class GetAudioComponent implements OnInit {
      constructor(private readonly mediaDevicesService: MediaDevicesService) {}
    
      @ViewChild('audio')
      audioRef: ElementRef<HTMLAudioElement>;
    
      localStream: MediaStream;
      mr: MediaRecorder;
      recordedChunks: any[] = [];
      private socket?: SocketIOClient.Socket;
    
      isStart = false;
    
      async ngOnInit() {
        await this._initLocalStream();
        await this._initSocket();
        // await this.ngAfterViewInit();
        await this._initMr();
      }
      private _initSocket() {
        this.socket = io(`https://dev.ajanuw.com:3333/audio`);
    
        this.socket.on(MESSAGE_EVENT, (data) => {
          this.saveFile(
            new Blob([data.audio], {
              type: data.type,
            })
          );
        });
      }
    
      private async _initLocalStream() {
        this.localStream = await this.mediaDevicesService.getUserMedia({
          audio: true,
        });
      }
    
      private async _initMr() {
        this.mr = new MediaRecorder(this.localStream);
        this.mr.addEventListener('dataavailable', (e: any) => {
          if (e.data.size > 0) this.recordedChunks.push(e.data);
        });
    
        this.mr.addEventListener('stop', () => {
          const type = 'audio/mp3; codecs=opus';
          const blob = new Blob(this.recordedChunks, {
            type,
          });
          this._sendServer(blob, type);
        });
      }
    
      saveFile(blob: Blob) {
        const downloadLink = document.createElement('a');
        downloadLink.href = URL.createObjectURL(blob);
        downloadLink.download = 'acetest.mp3';
        downloadLink.click();
      }
    
      ngAfterViewInit(): void {
        if (!this.localStream) return;
        this.audioRef.nativeElement.srcObject = this.localStream;
      }
    
      download() {
        this.isStart = false;
    
        this.mr.stop();
      }
    
      start() {
        this.isStart = true;
        this.mr.start();
      }
    
      /**
       * 将录制的audio blob发送给服务器
       */
      private async _sendServer(audio: Blob, type: string) {
        this.socket.emit(MESSAGE_EVENT, { audio, type });
      }
    }
    

    服务器

    import {
      SubscribeMessage,
      WebSocketGateway,
      WebSocketServer,
      OnGatewayConnection,
      OnGatewayDisconnect,
    } from '@nestjs/websockets';
    import { Socket } from 'socket.io';
    import { MESSAGE_EVENT } from '@live-video-example/p2p';
    
    @WebSocketGateway({ namespace: 'audio' })
    export class AudioGateway implements OnGatewayConnection, OnGatewayDisconnect {
      @WebSocketServer() server: Socket;
    
      handleDisconnect(client: Socket) {}
    
      handleConnection(client: Socket, ...args: any[]) {}
    
      @SubscribeMessage(MESSAGE_EVENT)
      onMessage(client: Socket, payload: any): any {
        console.log(payload);
    
        client.emit(MESSAGE_EVENT, payload);
      }
    }
    

    See also:

  • 相关阅读:
    再提一个建议,不过就要辛苦dudu了
    项目中的小项目实现在望
    Visual Studio.Net 技术Tip
    IQueryable与foreach的困惑?
    [转贴]浅析大型网站的架构
    [原创]WCF入门级使用教程(转载请注明出处)
    [原创]在msmq3.0中使用http协议发送消息
    [转贴][WCF Security] 4. 用户名/密码身份验证
    [转贴][WCF Security] 1. 基本概念
    [转]在SQL Server2005中进行错误捕捉
  • 原文地址:https://www.cnblogs.com/ajanuw/p/12746109.html
Copyright © 2011-2022 走看看