【问题标题】:Record Audio in Angular2在 Angular2 中录制音频
【发布时间】:2016-10-12 14:03:20
【问题描述】:

如何在 Angular2 中录制音频和播放。我看到https://logbon72.github.io/angular-recorder/ 但它是针对 AngularJS 的。 请帮帮我

【问题讨论】:

    标签: angular recorder


    【解决方案1】:

    现在我要在 Angular 2 中实现用于录音的 JRecorder 插件。首先从该 URL https://github.com/mattdiamond/Recorderjs 下载该插件。 现在该怎么办?

    1:首先在你的 angular2/src/assets/js 文件夹中创建一个文件 recorderFunctions.js 文件并在该文件中复制代码,代码是:

    function __log(e, data) {
        log.innerHTML += "\n" + e + " " + (data || '');
      }
    
      var audio_context;
      var recorder;
    
      function startUserMedia(stream) {
        var input = audio_context.createMediaStreamSource(stream);
        __log('Media stream created.');
    
        // Uncomment if you want the audio to feedback directly
        //input.connect(audio_context.destination);
        //__log('Input connected to audio context destination.');
        
        recorder = new Recorder(input);
        __log(recorder);
        __log('Recorder initialised.');
      }
    
      function startRecording(button) {
        recorder && recorder.record();
        __log('Recording...');
      }
    
      function stopRecording(button) {
        recorder && recorder.stop();
        __log('Stopped recording.');
        
        // create WAV download link using audio data blob
        createDownloadLink();
        
        recorder.clear();
      }
    
      function createDownloadLink() {
        recorder && recorder.exportWAV(function(blob) {
          var url = URL.createObjectURL(blob);
          var li = document.createElement('li');
          var au = document.createElement('audio');
          var hf = document.createElement('a');
          
          au.controls = true;
          au.src = url;
          hf.href = url;
          hf.download = new Date().toISOString() + '.wav';
          hf.innerHTML = hf.download;
          li.appendChild(au);
          li.appendChild(hf);
          recordingslist.appendChild(li);
        });
      }
    
    
     var recorderObject = (function() {
      return {
         recorder: function() {
            (function($) {
                'use strict';
      window.onload = function init() {
        try {
          // webkit shim
          window.AudioContext = window.AudioContext || window.webkitAudioContext;
          navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
          window.URL = window.URL || window.webkitURL;
          
          audio_context = new AudioContext;
          __log('Audio context set up.');
          __log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
        } catch (e) {
          alert('No web audio support in this browser!');
        }
        
        navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
          __log('No live audio input: ' + e);
        });
      };
    })(window.jQuery);
    }
    }
    })(recorderObject||{})

    2:现在还要从 mattdiamond/Recorderjs 的 dist 文件夹中复制文件 recorder.js 并将该文件也粘贴到您的 angular 2 src/assets/js 文件夹中。不要忘记在您的 Angular 2 index.html 文件中提供这两个文件的引用。

    3:现在打开你的终端并通过输入使用 angular-cli 创建组件

    ng g c audio-files
    

    4:在您的 audio-files.component.html 文件中,将代码粘贴到此处:

      <!-- START PAGE CONTENT WRAPPER -->
      <div class="page-content-wrapper ">
        <!-- START PAGE CONTENT -->
    	<div class="content ">
    
          <div class="container-fluid container-fixed-lg sm-p-l-20 sm-p-r-20">
            <div class="inner">
              <!-- START BREADCRUMB -->
               <ul class="breadcrumb">
                <li>
                  <i class="{{ dashboardIcon }}" aria-hidden="true"></i> <a routerLink="">Dashboard</a>
                </li>
                <li>
                  <i class="{{ audioIcon }}" aria-hidden="true"></i> <a style="cursor:pointer;" class="active">{{ breadcrum }}</a>
                </li>
              </ul>
              <!-- END BREADCRUMB -->
            </div>
          </div>
     
          <!-- START CONTAINER FLUID -->
          <div class="container-fluid container-fixed-lg bg-white">
            <!-- START PANEL -->
            <div class="panel panel-transparent">
              <h1>Recorder.js simple WAV export example</h1>
    
    		  <p>Make sure you are using a recent version of Google Chrome.</p>
    		  <p>Also before you enable microphone input either plug in headphones or turn the volume down if you want to avoid ear splitting feedback!</p>
    		
    		  <button class="btn btn-primary" id = "record" (click)="start(this);" [ngClass]='{disabled: isOn}'>record</button>
    		  <button class="btn btn-primary" id = "stop" (click)="stop(this);" [ngClass]='{disabled: isOff}'>stop</button>
    		  
    		  <h2>Recordings</h2>
    		  <ul id="recordingslist"></ul>
    		  
    		  <h2>Log</h2>
    		  <pre id="log"></pre>
    		 </div>
      <!-- END PANEL -->
    </div>
    
    </div>
    <!-- END PAGE CONTENT -->
    
    <!-- START FOOTER -->
    
    <!-- END FOOTER -->
    
    </div>
    <!-- END PAGE CONTENT WRAPPER -->

    5:在您的 audio-files.component.ts 文件中,将代码粘贴到此处:

    import { Component, OnInit } from '@angular/core';
    import { AppComponent } from '../../app.component';
    import { ElementRef } from '@angular/core';
    import { FormGroup, FormControl, FormBuilder, Validators } from "@angular/forms";
    import { AudioFileService } from "../../shared/_services/audio-file.service";
    import { NotificationService } from '../../shared/utils/notification.service';
    import { ConfigService } from '../../shared/utils/config.service';
    import { Router } from "@angular/router";
    import { Http,Response,Headers,RequestOptions, URLSearchParams } from "@angular/http";
    import { Observable } from "rxjs";
    declare var $:any;
    declare var recorderObject: any;
    declare function startRecording(button) : void;
    declare function stopRecording(button) : void;
    
    
    @Component({
      selector: 'app-audio-files',
      templateUrl: './audio-files.component.html',
      styleUrls: ['./audio-files.component.css']
    })
    export class AudioFilesComponent implements OnInit {
      breadcrum: string;
      dashboardIcon: string;
      audioIcon: string;
      isOn:boolean;
      isOff:boolean;
     
    
      constructor(private audioFileService:AudioFileService,
                  fb: FormBuilder,
      		      private notificationService: NotificationService,
      		      private elRef: ElementRef,
      		      private appComponent: AppComponent,
      		      private configService: ConfigService,
      		      private router: Router,
      		      private http: Http) { }
    
      ngOnInit() {
      	
      	 this.audioFileService.getAudioFiles()
      	  	.subscribe((res)=>{
      	  	 	this.breadcrum = res['breadcrum'];
      	  	 	this.dashboardIcon = res['dashboardIcon'];
      	  	 	this.audioIcon = res['audioIcon'];
      	  	},
      	  	error=>{
      	  		//this.notificationService.printErrorMessage('Warning','Failed to load MOH Files','danger');
      	  	});
      	this.isOn = false;
      	this.isOff = true;
      	recorderObject.recorder();
      	this.appComponent.isLogin = true;
    	this.appComponent.wrapper = 'page-container';
      }
      
      public start(button){
      	startRecording(button);
      	this.isOn = true;
        this.isOff = false;
      };
      
      public stop(button){
      	stopRecording(button);
      	this.isOn = false;
        this.isOff = true;
      }
      /*startRecording(button) {
        recorder && recorder.record();
        this.isOn = true;
        this.isOff = false;
    
        console.log('Recording.....');
      }*/
    
    }

    在该文件中,我声明了两个函数 startRecording(button) 和 stopRecording(button)。它们告诉我们如何调用外部 javascript 文件 recorderFunctions.js 中的 typescript 文件中的函数。我希望你能轻松实现它。快乐编码:)

    【讨论】:

    • 关于你的第二点:我已经添加了recorder.js文件。我需要添加更多的js文件吗?
    【解决方案2】:

    目前,我实现此功能只是使用 javascript。我正在编写一个组件或指令。参考: 1.https://webaudiodemos.appspot.com/AudioRecorder/index.html 2.https://github.com/mattdiamond/Recorderjs 这些代码可以在angular 2中使用,我已经测试过了。

    【讨论】:

      猜你喜欢
      • 2013-04-23
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 2019-02-25
      相关资源
      最近更新 更多