0

I have created an app where I am recording an audio in wav format and then replaying that audio and then posting it to api for further processing. But after posting data to api it says "not a wave file -- no riff header".

I tried this link also as reference.

Here is my javascript code of app:

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();
}

For recording I have used Media plugin. I am not able to figure out why this is happening.

Here is my api code

 [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;
        }
Sonali
  • 2,223
  • 6
  • 32
  • 69

1 Answers1

0

Try like below one,

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());
        }
Mohan Srinivas
  • 302
  • 3
  • 13
  • I think problem is in the way wav file is created. because I tried to create mp3 file then post it in the same way and then converting mp3 to wav...in that case also Mp3Reader class of NAudio is throwing error saying invalid mp3 file. – Sonali Feb 21 '18 at 16:26