【问题标题】:record wav file in cordova and upload to api在cordova中录制wav文件并上传到api
【发布时间】:2018-02-21 19:07:18
【问题描述】:

我创建了一个应用程序,我在其中以 wav 格式录制音频,然后重播该音频,然后将其发布到 api 以进行进一步处理。 但是在将数据发布到 api 之后,它说“不是波形文件——没有 riff 头”。

我也试过this link 作为参考。

这是我的应用程序的 javascript 代码:

var mediaVar = null;
var recordFileName = "recording.wav";
var mediaVarSrc = "cdvfile://localhost/sdcard/recording.wav";
var status = null;
var target = "";

document.getElementById("start-btn").addEventListener("click", function () {
    createMedia(function () {
        status = "recording";
        mediaVar.startRecord();
    }, onStatusChange);

    $("#recordingText").show();
});

document.getElementById("stop-btn").addEventListener("click", function () {
    stop();
});

function createMedia(onMediaCreated, mediaStatusCallback) {
    if (mediaVar != null) {
        onMediaCreated();
        return;
    }
    if (typeof mediaStatusCallback == 'undefined') {
        mediaStatusCallback = null;
    }
    window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, function (fileSystem) {
        fileSystem.getFile(recordFileName, {
            create: true,
            exclusive: false
        }, function (fileEntry) {
            fileUrl = fileEntry.toURL();
            mediaVar = new Media(fileUrl,
                function () {}, onError, mediaStatusCallback);
            onMediaCreated();
        }, onError);
    }, onError);
}

function stop() {
    alert("Stop");
    $("#recordingText").hide();
    if (mediaVar == null) {
        return;
    }
    if (status == 'recording') {
        mediaVar.stopRecord();
        mediaVar.release();
        status = 'stopped';
        play();
    } else {
        alert("Nothing stopped");
    }
}

function play() {
    if (mediaVar) {
        status = "playing";
        //playAudioFile(recordFileName);
        window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory + recordFileName, function (tempFile) {
            alert(JSON.stringify(tempFile));

            tempFile.file(function (tempWav) {
                alert(JSON.stringify(tempWav));
                var options = new FileUploadOptions();
                options.chunkedMode = false;
                options.fileKey = "file";
                options.fileName = recordFileName;
                options.mimeType = "audio/wav";
                var ft = new FileTransfer();
                ft.upload(tempFile.nativeURL, encodeURI(target), function () {
                    alert("Win");
                }, function () {
                    alert("false");
                }, options, true);
            });
        }, function (e) {
            console.log("Could not resolveLocalFileSystemURL: " + e.message);
        });
    }
}

var myMedia = null;

function playAudioFile(src) {
    myMedia = new Media(src,
        function () { },
        function (error) { },
        function (status) { }
    );
    myMedia.play();
}

function stopplay(calledfrom) {
    mediaVar.stop();
}


function recordAudio() {
    if (myMedia == null) {
        myMedia = new Media(srcurl,
            function () {
                console.log("recordAudio():Audio Success");
            },
            function (err) {
                console.log("recordAudio():Audio Error: " + err.code);
            });
    }
    myMedia.startRecord();
}

对于录制,我使用了媒体插件。我无法弄清楚为什么会这样。

这是我的 api 代码

 [HttpPost]
        [Route("UploadFile")]
        public string UploadFile()
        {
            string Result = String.Empty;
            string path = HttpContext.Current.Server.MapPath("~\\App_Data");
            string convertedFileName = "convert.wav";
            try
            {
                if (!Request.Content.IsMimeMultipartContent("form-data"))
                {
                    new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }
                else
                {
                    MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(path);
                    Task.Run(async () =>
                    {
                        await Request.Content.ReadAsMultipartAsync(streamProvider);
                    }).Wait();

                    var file = streamProvider.FileData[0];
                    FileInfo fileInfo = new FileInfo(file.LocalFileName);
                    string fileName = fileInfo.Name;

                    if (System.IO.File.Exists(path + "\\" + fileName))
                    {
                        using (WaveFileReader reader = new WaveFileReader(path + "\\" + fileName))
                        {
                            WaveFormat format = new WaveFormat(16000, 16, 1);
                            using (WaveFormatConversionStream convert = new WaveFormatConversionStream(format, reader))
                            {
                                WaveFileWriter.CreateWaveFile(path + "\\" + convertedFileName, convert);
                                convert.Close();
                            }
                            reader.Close();
                        }

                        System.IO.File.Delete(path + "\\" + fileName);


                        BingSpeechToText obj = new BingSpeechToText();
                        STTResponse _STTResponse = obj.ConvertAudio(path + "\\" + convertedFileName);

                        if (_STTResponse.Status && !String.IsNullOrEmpty(_STTResponse.Response))
                        {
                            Result = _STTResponse.Response;
                        }
                        else
                        {
                            Result = "No Result";
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                Result = ex.Message;
            }
            finally
            {
                if (System.IO.File.Exists(path + "\\" + convertedFileName))
                    System.IO.File.Delete(path + "\\" + convertedFileName);
            }
            return Result;
        }

【问题讨论】:

  • 你的api请求码在哪里?如果您添加了多部分表单数据,请将 req 更改为 request.setEntity(new FileEntity(new File("test.wav"), ContentType.APPLICATION_OCTET_STREAM));
  • @MohanSrinivas 这是我的 api 代码...请参阅我的问题。
  • 你使用的是哪个 api?cognitive?
  • 是的...语音转文本 api。
  • 在您的 api 代码中没有注意到 api url?您从哪里获取代码?如果您使用的是 sdk,则意味着正确阅读文档。

标签: javascript c# html cordova cordova-plugins


【解决方案1】:

像下面这样试试,

static String API_KEY = "YOUR-KEY";
static String PROFILE_ID = "YOUR-PROFILE-ID";
static String LOCATION = "westus"; 
HttpClient httpclient = HttpClients.createDefault();

        try {
            URIBuilder builder = new URIBuilder(
                String.format("https://%s.api.cognitive.microsoft.com/spid/v1.0/identificationProfiles/%s/enroll", LOCATION, PROFILE_ID));
            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);
            request.setHeader("Ocp-Apim-Subscription-Key", API_KEY);
            request.setEntity(new FileEntity(new File("test.wav"), ContentType.APPLICATION_OCTET_STREAM));

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            // Response is empty on success; the following will contain the URI where you can check the status
            System.out.println(response.getHeaders("Operation-Location")[0].getValue());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

【讨论】:

  • 我认为问题出在 wav 文件的创建方式上。因为我尝试创建 mp3 文件,然后以相同的方式发布它,然后将 mp3 转换为 wav ......在这种情况下,NAudio 的 Mp3Reader 类也会抛出错误,说无效的 mp3 文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 2020-05-18
  • 2014-03-12
  • 1970-01-01
相关资源
最近更新 更多