audio-recorder.component.ts 7.67 KB
Newer Older
liujiaxin's avatar
liujiaxin committed
1
import {ApplicationRef, ChangeDetectorRef, Component, EventEmitter, Input, OnDestroy, OnInit, Output, NgZone, OnChanges} from '@angular/core';
liujiangnan's avatar
liujiangnan committed
2 3
import {NzMessageService, NzNotificationService, UploadFile} from 'ng-zorro-antd';
import {HttpClient, HttpEvent, HttpEventType, HttpRequest} from '@angular/common/http';
liujiaxin's avatar
liujiaxin committed
4
import {environment} from '../../../environments/environment';
liujiangnan's avatar
liujiangnan committed
5 6 7 8 9 10 11

declare var Recorder;

@Component({
  selector: 'app-audio-recorder',
  templateUrl: './audio-recorder.component.html',
  styleUrls: ['./audio-recorder.component.scss']
liujiaxin's avatar
liujiaxin committed
12
})
liujiangnan's avatar
liujiangnan committed
13 14 15 16 17 18 19 20 21
export class AudioRecorderComponent implements OnInit, OnChanges, OnDestroy {
  _audioUrl: string;
  audio = new Audio();
  playIcon = 'play';
  isPlaying = false;
  isRecording = false;
  isUploading = false;
  type = Type.UPLOAD; // record | upload
  Type = Type;
22
  @Input()
liujiangnan's avatar
liujiangnan committed
23 24
  withRmBtn = false;

25 26
  uploadUrl;
  uploadData;
liujiangnan's avatar
liujiangnan committed
27

liujiangnan's avatar
liujiangnan committed
28 29 30 31 32 33 34 35
  @Input()
  needRemove = false;

  @Input()
  audioItem: any = null;

  @Input()
  set audioUrl(url) {
liujiaxin's avatar
liujiaxin committed
36
    this._audioUrl = url;
liujiangnan's avatar
liujiangnan committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    if (url) {
      this.audio.src = this._audioUrl;
      this.audio.load();
    }
    this.init();
  }

  get audioUrl() {
    return this._audioUrl;
  }

  @Output() audioUploaded = new EventEmitter();
  @Output() audioUploadFailure = new EventEmitter();
  @Output() audioRemoved = new EventEmitter();
  percent = 0;
  progress = 0;
  recorder: any;
  audioBlob: any;

liujiaxin's avatar
liujiaxin committed
56

liujiaxin's avatar
liujiaxin committed
57 58 59
  constructor( private nzMessageService: NzMessageService,
               private zone: NgZone,
               private nzNotificationService: NzNotificationService,
liujiaxin's avatar
liujiaxin committed
60 61
               private appRef: ApplicationRef,
               private changeDetectorRef: ChangeDetectorRef,
liujiaxin's avatar
liujiaxin committed
62
               private httpClient: HttpClient) {
63 64
    this.uploadUrl = (<any> window).courseware.uploadUrl();
    this.uploadData = (<any> window).courseware.uploadData();
liujiangnan's avatar
liujiangnan committed
65

66 67 68 69
    window['air'].getUploadCallback = (url, data) => {
      this.uploadUrl = url;
      this.uploadData = data;
    };
liujiaxin's avatar
liujiaxin committed
70 71 72 73 74 75 76 77 78 79 80 81
    this.recorder = new Recorder({
      sampleRate: 44100, // 采样频率,默认为44100Hz(标准MP3采样率)
      bitRate: 128, // 比特率,默认为128kbps(标准MP3质量)
      success: () => { // 成功回调函数
      },
      error: (msg) => { // 失败回调函数
        this.nzNotificationService.error('Init Audio Recorder Failed', msg, {nzDuration: 0});
      },
      fix: (msg) => { // 不支持H5录音回调函数
        this.nzNotificationService.error('Init Audio Recorder Failed', msg, {nzDuration: 0});
      }
    });
liujiangnan's avatar
liujiangnan committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  }

  init() {
    this.playIcon = 'play';
    this.isPlaying = false;
    this.isRecording = false;
    this.isUploading = false;
    this.percent = 0;
    this.progress = 0;
    this.audioBlob = null;
  }
  ngOnChanges() {
    // if (!this.audioItem || !this.audioItem.type) {
    //   return;
    // }
    // this.beforeUpload(this.audioItem);
  }
  ngOnInit() {
liujiangnan's avatar
liujiangnan committed
100

liujiangnan's avatar
liujiangnan committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    this.audio.onplay = () => {
      this.onPlay();
    };
    this.audio.onpause = () => {
      this.onPause();
    };
    this.audio.ontimeupdate = (event) => {
      this.onTimeUpdate(event);
    };
    this.audio.onended = (event) => {
      this.onEnded();
    };
  }

  ngOnDestroy() {
    this.audio.pause();
    this.isPlaying = false;
    this.audio.remove();
liujiaxin's avatar
liujiaxin committed
119 120 121
    if (this.recorder.worker) {
      this.recorder.worker.terminate();
    }
liujiangnan's avatar
liujiangnan committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  }

  progressText(percent) {
    return ``;
  }

  onPlay() {
    console.log('play');
    this.playIcon = 'pause';
    this.isPlaying = true;
  }

  onPause() {
    console.log('pause');
    this.playIcon = 'play';
    this.isPlaying = false;
  }

  onEnded() {
    console.log('on end');
    this.playIcon = 'play';
    this.percent = 0;
    this.isPlaying = false;
  }

  onTimeUpdate(event) {
    this.percent = Math.floor((this.audio.currentTime / this.audio.duration) * 100);
  }

  onBtnPlay() {
    if (this.isRecording) {
      this.nzMessageService.warning('In Recording');
      return;
    }
    if (this.isPlaying) {
      this.audio.pause();
    } else {
      this.audio.play();
    }
  }

  // 开始录音
liujiaxin's avatar
liujiaxin committed
164
  onBtnRecord = () => {
liujiaxin's avatar
liujiaxin committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    if (!this.isRecording) {
      this.isRecording = true;
      this.recorder.start();
    } else {
      this.isRecording = false;
      this.recorder.stop();
      this.recorder.getBlob((blob) => {
        this.audio.src = URL.createObjectURL(blob);
        this.audioBlob = blob;
        this.isUploading = true;
        const formData = new FormData();
        formData.append('file', blob, 'courseware-item-record.mp3');
        const req = new HttpRequest('POST', this.uploadUrl, formData, {
          reportProgress: true
        });

        this.httpClient.request(req)
          .subscribe((event: HttpEvent<any>) => {
            switch (event.type) {
              case HttpEventType.UploadProgress:
                this.zone.run(() => {
                  this.progress = Math.floor(100 * event.loaded / event.total);
                });
                break;
              case HttpEventType.Response:
                this.zone.run(() => {
                  console.log(event);
                  this.audioUploaded.emit(event.body);
                  this.isUploading = false;
                });
                break;
            }
          }, (error) => {
            console.error(error);
            this.isUploading = false;
          });
      });
    }
liujiangnan's avatar
liujiangnan committed
203 204 205
  }

  // 切换模式
liujiaxin's avatar
liujiaxin committed
206
  onBtnSwitchType() {
liujiaxin's avatar
liujiaxin committed
207 208 209 210 211 212 213 214 215 216 217 218
    if (this.isUploading) {
      this.nzMessageService.warning('In Uploading');
      return;
    } else if (this.isRecording) {
      this.nzMessageService.warning('In Recording');
      return;
    }
    if (this.type === Type.RECORD) {
      this.type = Type.UPLOAD;
    } else {
      this.type = Type.RECORD;
    }
liujiaxin's avatar
liujiaxin committed
219 220 221 222 223 224 225 226
    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
    this.refresh();
  }
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
liujiangnan's avatar
liujiangnan committed
227 228
  }
  onBtnClearAudio() {
229
    this.audioUrl = null;
liujiangnan's avatar
liujiangnan committed
230 231 232 233 234 235 236 237
    this.audioRemoved.emit();
  }

  onBtnDeleteAudio() {
    this.audioUrl = null;
    this.audioRemoved.emit();
  }

liujiaxin's avatar
liujiaxin committed
238
  handleChange(info: { type: string, file: UploadFile, event: any }): void {
liujiangnan's avatar
liujiangnan committed
239 240 241 242 243 244 245
    switch (info.type) {
      case 'start':
        this.isUploading = true;
        this.progress = 0;
        break;
      case 'success':
        this.isUploading = false;
liujiangnan's avatar
liujiangnan committed
246
        this.uploadSuccess(info.file.response);
liujiangnan's avatar
liujiangnan committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        this.audioUploaded.emit(info.file.response);
        break;
      case 'progress':
        this.progress = parseInt(info.event.percent, 10);
        break;
    }
  }
  checkSelectFile(file: any) {
    if (!file) {
      return;
    }
    const isAudio = ['audio/mp3', 'audio/wav', 'audio/ogg'].includes(file.type);
    if (!isAudio) {
      this.nzMessageService.error('You can only upload Audio file ( mp3 | wav |ogg)');
      return;
    }
    const delta =  25;
    const isOverSize = (file.size / 1024 / 1024) < delta;
    if (!isOverSize) {
      this.nzMessageService.error(`audio file  must smaller than ${delta}MB!`);
      return false;
    }
    return true;
  }
liujiaxin's avatar
liujiaxin committed
271
  beforeUpload = (file: File) => {
liujiangnan's avatar
liujiangnan committed
272 273 274

    this.audioUrl = null;
    if (!this.checkSelectFile(file)) {
liujiangnan's avatar
liujiangnan committed
275
      return false;
liujiangnan's avatar
liujiangnan committed
276 277
    }
    this.isUploading = true;
liujiaxin's avatar
liujiaxin committed
278
    this.progress = 0;
liujiangnan's avatar
liujiangnan committed
279
  }
liujiaxin's avatar
liujiaxin committed
280 281 282 283
  uploadSuccess = (url) => {
    this.nzMessageService.info('Upload Success');
    this.isUploading = false;
    this.audioUrl = url;
liujiangnan's avatar
liujiangnan committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
  }
  uploadFailure = (err, file) => {
    this.isUploading = false;
    if (err.name && err.name === 'cancel') {
      return;
    }
    console.log(err);
    this.nzMessageService.error('Upload Error ' + err.message);
    this.audioUploadFailure.emit(file);
  }
  doProgress = (p) => {
    if (p > 1) {
      p = 1;
    }
    if (p < 0) {
      p = 0;
    }
    // console.log(Math.floor(p * 100));
    this.progress =  Math.floor(p * 100);
  }

}

enum Type {
  RECORD = 1, UPLOAD
}