使用FlashWavRecorder實現瀏覽器錄製wav音頻和上傳音頻文件,兼容IE8以上瀏覽器

  • 2019 年 11 月 1 日
  • 筆記

版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/eguid_1/article/details/53183256

前言:本項目基於github開源插件實現,該插件使用flash實現,兼容IE8以上瀏覽器

感謝michalstocki的分享該項目,github項目地址:https://github.com/michalstocki/FlashWavRecorder

部落客修改後的項目下載地址:http://download.csdn.net/detail/eguid_1/9684124

1、要提交的表單(如果只需要上傳文件,可以不需要)

<form id="uploadForm" name="uploadForm" action="audio/send" method="post">        <span>設備id:</span><input name="deviceId" value="0000007"><!-- 設備id -->        <span>音頻格式:</span><input name="audio_format" value="wav"><!-- 音頻格式 -->      </form>

2、修改表單名和上傳的音頻文件名

這兩個參數用來修改上傳的表單和要上傳的已經錄製好的音頻文件名,與後台的文件接收的參數名一致

FWRecorder.uploadFormId = "#uploadForm";//要上傳的表單 FWRecorder.uploadFieldName = "audio_file";//上傳文件的參數名

$(function () {    var $uploadStatus = $('#upload_status'),      $showLevelButton = $('.show_level'),      $hideLevelButton = $('.hide_level'),      $level = $('.control_panel .level');      var CLASS_CONTROLS = "control_panel";    var CLASS_RECORDING = "recording";    var CLASS_PLAYBACK_READY = "playback_ready";    var CLASS_PLAYING = "playing";    var CLASS_PLAYBACK_PAUSED = "playback_paused";    //  Embedding flash object ---------------------------------------------------------------------------------------------      setUpFormOptions();    var appWidth = 24;    var appHeight = 24;    var flashvars = {'upload_image': 'audioRecorder/upload.png'};    var params = {};    var attributes = {'id': "recorderApp", 'name': "recorderApp"};    swfobject.embedSWF("audioRecorder/recorder.swf", "flashcontent", appWidth, appHeight, "11.0.0", "", flashvars, params, attributes);    //  Handling FWR events ------------------------------------------------------------------------------------------------      window.fwr_event_handler = function fwr_event_handler() {      $('#status').prepend("<div class="recorder-event">" + arguments[0] + "</div>");      var name, $controls;      switch (arguments[0]) {        case "ready":          var width = parseInt(arguments[1]);          var height = parseInt(arguments[2]);          FWRecorder.uploadFormId = "#uploadForm";//要上傳的表單          FWRecorder.uploadFieldName = "audio_file";//上傳文件的參數名          FWRecorder.connect("recorderApp", 0);          FWRecorder.recorderOriginalWidth = width;          FWRecorder.recorderOriginalHeight = height;          $('.save_button').css({'width': width, 'height': height});          break;          case "no_microphone_found":          break;          case "microphone_user_request":          recorderEl().addClass("floating");          FWRecorder.showPermissionWindow();          break;          case "microphone_connected":          FWRecorder.isReady = true;          $uploadStatus.css({'color': '#000'});          break;          case "permission_panel_closed":          FWRecorder.defaultSize();          recorderEl().removeClass("floating");          break;          case "microphone_activity":          $('#activity_level').text(arguments[1]);          break;          case "recording":          name = arguments[1];          $controls = controlsEl(name);          FWRecorder.hide();          setControlsClass($controls, CLASS_RECORDING);          break;          case "recording_stopped":          name = arguments[1];          $controls = controlsEl(name);          var duration = arguments[2];          FWRecorder.show();          setControlsClass($controls, CLASS_PLAYBACK_READY);          $('#duration').text(duration.toFixed(4) + " 秒");          break;          case "microphone_level":          $level.css({width: arguments[1] * 50 + '%'});          break;          case "observing_level":          $showLevelButton.hide();          $hideLevelButton.show();          break;          case "observing_level_stopped":          $showLevelButton.show();          $hideLevelButton.hide();          $level.css({width: 0});          break;          case "playing":          name = arguments[1];          $controls = controlsEl(name);          setControlsClass($controls, CLASS_PLAYING);          break;          case "playback_started":          name = arguments[1];          var latency = arguments[2];          break;          case "stopped":          name = arguments[1];          $controls = controlsEl(name);          setControlsClass($controls, CLASS_PLAYBACK_READY);          break;          case "playing_paused":          name = arguments[1];          $controls = controlsEl(name);          setControlsClass($controls, CLASS_PLAYBACK_PAUSED);          break;          case "save_pressed":          FWRecorder.updateForm();          break;          case "saving":          name = arguments[1];          break;          case "saved":          name = arguments[1];          var data = $.parseJSON(arguments[2]);          if (data.status) {            $('#upload_status').css({'color': '#0F0'}).text(name + " 上傳成功");          } else {            $('#upload_status').css({'color': '#F00'}).text(name + " 上傳失敗");          }          break;          case "save_failed":          name = arguments[1];          var errorMessage = arguments[2];          $uploadStatus.css({'color': '#F00'}).text(name + " 失敗: " + errorMessage);          break;          case "save_progress":          name = arguments[1];          var bytesLoaded = arguments[2];          var bytesTotal = arguments[3];          $uploadStatus.css({'color': '#000'}).text(name + " 進展: " + bytesLoaded + " / " + bytesTotal);          break;      }    };    //  Helper functions ---------------------------------------------------------------------------------------------------      function setUpFormOptions() {      var gain = $('#gain')[0];      var silenceLevel = $('#silenceLevel')[0];      for (var i = 0; i <= 100; i++) {        gain.options[gain.options.length] = new Option(100 - i);        silenceLevel.options[silenceLevel.options.length] = new Option(i);      }    }      function setControlsClass($controls, className) {      $controls.attr('class', CLASS_CONTROLS + ' ' + className);    }      function controlsEl(name) {      return $('#recorder-' + name);    }      function recorderEl() {      return $('#recorderApp');    }      //  Button actions -----------------------------------------------------------------------------------------------------      window.microphonePermission = function () {      recorderEl().addClass("floating");      FWRecorder.showPermissionWindow({permanent: true});    };      window.configureMicrophone = function () {      if (!FWRecorder.isReady) {        return;      }      FWRecorder.configure($('#rate').val(), $('#gain').val(), $('#silenceLevel').val(), $('#silenceTimeout').val());      FWRecorder.setUseEchoSuppression($('#useEchoSuppression').is(":checked"));      FWRecorder.setLoopBack($('#loopBack').is(":checked"));    };    });

3、後台接收文件

接收前端三個參數:deviceId,audio_format,audio_file

audio_file就是音頻文件

public int sendAudioData(@RequestParam(value = "deviceId") String deviceId,  			@RequestParam(value = "audio_format") String audio_format, @RequestParam("audio_file") MultipartFile file) {  		boolean ret=false;  		File tFile = null;  		System.out.println(audio_format + "," + deviceId);  		String fileName=null;  		// 判斷文件是否為空  		if (file != null && !file.isEmpty()&&(fileName=file.getName()+System.currentTimeMillis())!=null) {  			String filePath = Util.getRootPath() + fileName + ".wav";  			System.out.println("文件保存路徑:" +filePath);  			tFile = new File(filePath);    			try {  				// 轉存文件  				file.transferTo(tFile);  				ret=true;  			} catch (Exception e) {  				e.printStackTrace();  			}  		}  		if(ret=true){  		return 0;  		}  		return -1;  	}

4、最終效果