javascript 使用带有 HTML5 的用户麦克风录制音频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25101037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:57:09  来源:igfitidea点击:

Record Audio Using the Users Microphone with HTML5

javascriptjqueryhtmlhtml5-audioaudio-recording

提问by three3

I am very close to having a little project of mine done, however, I have run into a slight problem I cannot seem to figure out on my own. What I ultimately want to do is record a user's voice from the users microphone, and then upload the recording to my server when they are done. I am using the code from this project: https://github.com/cwilso/AudioRecorder

我非常接近完成我的一个小项目,但是,我遇到了一个我自己似乎无法解决的小问题。我最终想要做的是从用户麦克风录制用户的声音,然后在完成后将录音上传到我的服务器。我正在使用这个项目的代码:https: //github.com/cwilso/AudioRecorder

It works great, but I am needing to add a feature that it does not include out of the box. I need to be able to upload the file to my server after the recording has finished. With the default code, the file can be downloaded locally to my computer, but not uploaded. So I did some research and I came across another similar project that has the uploading feature. However, the rest of the project is more buggy in my opinion. So I tried adding the "uploading code" from the following project: https://github.com/nusofthq/Recordmp3js

它工作得很好,但我需要添加一个开箱即用的功能。录制完成后,我需要能够将文件上传到我的服务器。使用默认代码,文件可以本地下载到我的电脑,但不能上传。所以我做了一些研究,我遇到了另一个具有上传功能的类似项目。但是,在我看来,项目的其余部分有更多问题。所以我尝试从以下项目中添加“上传代码”:https: //github.com/nusofthq/Recordmp3js

Javascript code:

Javascript代码:

function uploadAudio(mp3Data){
    var reader = new FileReader();
    reader.onload = function(event){
        var fd = new FormData();
        var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
        console.log("mp3name = " + mp3Name);
        fd.append('fname', mp3Name);
        fd.append('data', event.target.result);
        $.ajax({
            type: 'POST',
            url: 'upload.php',
            data: fd,
            processData: false,
            contentType: false
        }).done(function(data) {
            //console.log(data);
            log.innerHTML += "\n" + data;
        });
    };      
    reader.readAsDataURL(mp3Data);
}

PHP code:

PHP代码:

<?php
if(!is_dir("recordings")){
    $res = mkdir("recordings",0777); 
}

// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
$filename = urldecode($_POST['fname']);

// write the data out to the file
$fp = fopen('recordings/'.$filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>

I have tried combining this code to the project located at https://github.com/cwilso/AudioRecorder, but to no avail. What do I need to change in the Javascript code above and where do I need to place it? Any help is greatly appreciated!

我曾尝试将此代码与位于https://github.com/cwilso/AudioRecorder的项目结合起来,但无济于事。我需要在上面的 Javascript 代码中更改什么以及我需要将它放在哪里?任何帮助是极大的赞赏!

PS: I know this only works in Chrome, FireFox, and Opera.

PS:我知道这只适用于 Chrome、FireFox 和 Opera。

回答by tpdietz

I have recently implemented a similar task you are trying to achieve using similar resources. You havent indicated that you need the audio uploaded as an mp3, so I am going to just show you how to upload a wav using recorderjs, using the source found here: https://github.com/cwilso/AudioRecorder

我最近实现了一个类似的任务,你试图使用类似的资源来实现。您还没有表示您需要将音频上传为 mp3,所以我将向您展示如何使用 recorderjs 上传 wav,使用此处找到的源:https: //github.com/cwilso/AudioRecorder

First things to note, recorderjs stores the uncompressed wav in a var called blob. This happens on line 101 of recorder js, more specifically in this function:

首先要注意的是,recorderjs 将未压缩的 wav 存储在一个名为 blob 的 var 中。这发生在记录器 js 的第 101 行,更具体地说是在这个函数中:

worker.onmessage = function(e){
  var blob = e.data;
  currCallback(blob);
}

The problem is that blob is locally declared in that function. We need to use it again, so for the sake of this example lets make it really easy to reach and make it global. So declare a variable blob outside of recorder js like so:

问题是 blob 是在该函数中本地声明的。我们需要再次使用它,所以为了这个例子,让我们让它真的很容易到达并使它成为全球性的。因此,在记录器 js 之外声明一个变量 blob,如下所示:

var blob = null;

Then modify the above function in recorderjs to store the data inside the globally declared 'blob' variable, the function should look like so:

然后在recorderjs中修改上面的函数,将数据存储在全局声明的'blob'变量中,函数应该是这样的:

worker.onmessage = function(e){
  blob = e.data;
  currCallback(blob);
}

Now we can use 'blob'. Now declare the following function somewhere,

现在我们可以使用'blob'。现在在某处声明以下函数,

function uploadAudio(){
        var fd = new FormData();
        var wavName = encodeURIComponent('audio_recording_' + new Date().getTime() + '.wav');
        console.log("wavName = " + wavName);
        fd.append('fname', wavName);
        fd.append('data', blob);
        $.ajax({
            type: 'POST',
            url: 'upload.php',
            data: fd,
            processData: false,
            contentType: false
        }).done(function(data) {
            //console.log(data);
            log.innerHTML += "\n" + data;
        });
}

Your server side code should use this:

您的服务器端代码应该使用这个:

<?php
if(!is_dir("recordings")){
    $res = mkdir("recordings",0777); 
}
move_uploaded_file($_FILES["file"]["tmp_name"],
  $res . $_FILES["file"]["fname"]);
?>

Note: $_FILES["file"]["tmp_name"] is what it sounds like. A temporary location of the file. This is done for you with the ajax call and form data.

注意:$_FILES["file"]["tmp_name"] 就是这个意思。文件的临时位置。这是通过 ajax 调用和表单数据为您完成的。

Good luck, let me know if you run into problems.

祝你好运,如果遇到问题,请告诉我。

回答by K Lee

As?far as?I?can see, AudioRecorder exports as?Blob. Blobs are something you can easily upload with XMLHttpRequest (and XMLHttpRequest uploads are something you can easily figure out with Google). In?short, you don't need FileReader(and may even skip FormData, since you're only uploading a?single Blob).

据我所知,AudioRecorder 导出为 Blob。Blob 是您可以使用 XMLHttpRequest 轻松上传的东西(而 XMLHttpRequest 上传是您可以使用 Google 轻松搞定的东西)。简而言之,您不需要FileReader(甚至可能会跳过FormData,因为您只上传了一个?单个 Blob)。

Keep in?mind that people tend to?not?answer questions indicating no?prior analysis by?the?OP; in?this case you should have explained at?least a) what kind of?data you have to?upload, and b) what exactly doesn't work in?you existing implementation. Here, you're effectively asking people to?cross two libraries (most of?us never used either one, not?to?mention both). The?truth is?I?might be?wrong about Blobs, but you actually know that better than?me and just failed to?inform. (Don't get me?wrong, though; I?hope I'm?right, and you're gonna get your code working soon.)

请记住,人们倾向于“不”回答表明没有事先分析的问题?OP;在这种情况下,您应该至少解释一下 a) 您必须上传什么样的数据?上传,以及 b) 什么在您现有的实现中不起作用。在这里,您实际上是在要求人们跨越两个图书馆(我们中的大多数人从来没有使用过任何一个,而不是提到两个)。事实是?我?可能对 Blob 是错误的,但你实际上比我更了解这一点,只是没能告知。(别误会我?不过;我?希望我是对的?你很快就会让你的代码工作。)