Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all
while uploading audio file to the server response is not getting ..
Getting this error "The remote server returned an error: (400) Bad Request."

please provide soultion regarding this..

thanks

What I have tried:

View page :-
-----------

@model Beyond_Verbal_API.Models.BeyondModel
@{
    ViewBag.Title = "Beyond Verbal";
    
}

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Live input record and playback</title>
    <style type='text/css'>
        ul {
            list-style: none;
        }

        #recordingslist audio {
            display: block;
            margin-bottom: 10px;
        }
    </style>
</head>                  
<body>                                
                     
    @*<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 id="btnPlay" onclick="startRecording(this);">record</button>
    <button id="btnStop" onclick="stopRecording(this);" disabled>stop</button>

    <br /><br />
    @*<div>
        <table>
            <tr>
                <td><button id="btnTable" onclick="show('Table');">Table      </button></td>
                <td><button id="btnJson" onclick="show('Json');">JSon</button></td>
            </tr>
        </table>
    </div>*@
    <div>
        <br />
        <div id="divJson"></div>
        <table class="table table-striped table-hover table-bordered" id="resultTable">
            <thead>
                <tr>
                    <th class="center">Temper</th>
                    <th class="center">Valence</th>
                    <th class="center">Arousal</th>
                    <th class="center">Group</th>
                    <th class="center">Composite</th>
                </tr>
            </thead>

            <tbody id="results"></tbody>
        </table>

    </div>
    <br />
    <br />

    <h2>Recordings</h2>
    <ul id="recordingslist"></ul>   

    <h2>Log</h2>
    <pre id="log">



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 initialised.');
}

function startRecording(button) {
recorder && recorder.record();
button.disabled = true;
button.nextElementSibling.disabled = false;
__log('Recording...');
}

function stopRecording(button) {
recorder && recorder.stop();
button.disabled = true;
button.previousElementSibling.disabled = false;
__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 xhr = new XMLHttpRequest();
var url = '/Home/AudioUpload';
xhr.open("POST", url, true);


xhr.onreadystatechange = function () {

if (xhr.readyState == 4) {
var data = xhr.responseText; //.replace(/,"/g, '<br/>');
if (data == "Result not Found" || data == "Error") {
alert(data);

}
else {
var jsonResponse = JSON.parse(data);
alert(data);
var row = "";
row += "<tr><td>" + jsonResponse["Temper"] + "</td>"
+ "<td>" + jsonResponse["Valence"] + " </td>"
+ "<td>" + jsonResponse["Arousal"] + " </td>"
+ "<td>" + jsonResponse["GroupPrimary"] + jsonResponse["GroupSecondary"] + " </td>"
+ "<td>" + jsonResponse["CompositePrimary"] + jsonResponse["CompositeSecondary"] + " </td>&lt;//tr>"
;


$("#results").html(row);

document.getElementById("divJson").innerHTML = data.replace(/,"/g, '<br/>');;
}
}
}
xhr.send(blob);

});
}

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









Controller page
---------------

[AllowAnonymous]
 public ActionResult BeyondVerbal()
 {
     return View();
 }

 [HttpPost]
 public JsonResult AudioUpload()
 {
     string path = Server.MapPath("~/AudioRecording/");

     string filename = "Recording_" + DateTime.UtcNow.ToString("dd-mm-yyyy") + "" + ".wav";
     string Inputpath = path + filename;
     Request.SaveAs(Inputpath,false);

   string tokenUrl = "https://token.beyondverbal.com/token";
   string apiKey = "19794eb7-8a75-4823-b181-745c40116f92";
   string startUrl = "https://apiv3.beyondverbal.com/v1/recording/";


     var requestData = "apiKey=" + apiKey + "&grant_type=client_credentials";
     //auth
     var token = authRequest(tokenUrl, Encoding.UTF8.GetBytes(requestData));
     //start
     var startResponseString = CreateWebRequest(startUrl + "start", Encoding.UTF8.GetBytes("{ dataFormat: { type: \"WAV\" } }"), token);
     var startResponseObj = JsonConvert.DeserializeObject<dynamic>(startResponseString);
     if (startResponseObj.status != "success")
     {
         Console.WriteLine("Response Status: " + startResponseObj.status);
         //return Json(startResponseObj.status, JsonRequestBehavior.AllowGet);
     }
     var recordingId = startResponseObj.recordingId.Value;

     ////analysis
     string analysisUrl = startUrl + recordingId;
     var bytes = System.IO.File.ReadAllBytes(Inputpath);
     var analysisResponseString = CreateWebRequest(analysisUrl, bytes, token);
     analysisResponseString = analysisResponseString.Replace("][", ",");
     dynamic resultJson;
     resultJson = JsonConvert.DeserializeObject(analysisResponseString);
     dynamic result = resultJson["result"];
     dynamic AnalysisResult = result["analysisSummary"]["AnalysisResult"];
     dynamic analysisSegments = result["analysisSegments"][0]["analysis"];

     Result res = new Result();
     res.Temper = AnalysisResult["Temper"]["Mode"];
     res.Valence = AnalysisResult["Valence"]["Mode"];
     res.Arousal = AnalysisResult["Arousal"]["Mode"];
     res.GroupP = analysisSegments["Mood"]["Group11"]["Primary"]["Phrase"];
     res.GroupS = analysisSegments["Mood"]["Group11"]["Secondary"]["Phrase"];
     res.CompositeP = analysisSegments["Mood"]["Composite"]["Primary"]["Phrase"];
     res.CompositeS = analysisSegments["Mood"]["Composite"]["Secondary"]["Phrase"];



     var Values = new
     {
         Temper= res.Temper,
         Valence= res.Valence,
         Arousal= res.Arousal,
         GroupPrimary=res.GroupP,
         GroupSecondary=res.GroupS,
         CompositePrimary=res.CompositeP,
         CompositeSecondary=res.CompositeS
     };

      return Json(Values,JsonRequestBehavior.AllowGet);


 }

 private static string authRequest(string url, byte[] data)
 {
     JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings() { Formatting = Formatting.Indented };
     HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
     request.Method = "POST";
     request.ContentType = "application/x-www-form-urlencoded";
     request.ServicePoint.SetTcpKeepAlive(false, 0, 0);
     request.ServicePoint.UseNagleAlgorithm = false;
     request.ReadWriteTimeout = 1000000;
     request.Timeout = 10000000;
     request.SendChunked = false;
     request.AllowWriteStreamBuffering = true;
     request.AllowReadStreamBuffering = false;
     request.KeepAlive = true;

     using (var requestStream = request.GetRequestStream())
     {
         requestStream.Write(data, 0, data.Length);
     }

     using (var response = request.GetResponse() as HttpWebResponse)
     using (var responseStream = response.GetResponseStream())
     using (var streamReader = new System.IO.StreamReader(responseStream, Encoding.UTF8))
     {
         var res = streamReader.ReadToEnd();
         dynamic responceContent = JsonConvert.DeserializeObject(res, jsonSerializerSettings);
         return responceContent.access_token;
     }
 }

 private static string CreateWebRequest(string url, byte[] data, string token = null)
 {
     JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings() { Formatting = Formatting.Indented };
     HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
     request.Method = "POST";
     request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

     request.KeepAlive = true;
     request.ServicePoint.SetTcpKeepAlive(true, 10000, 10000);

     request.Timeout = 10000000;
     request.SendChunked = false;
     request.AllowWriteStreamBuffering = true;
     request.AllowReadStreamBuffering = false;
     if (string.IsNullOrEmpty(token) == false)
         request.Headers.Add("Authorization", "Bearer " + token);

     using (var requestStream = request.GetRequestStream())
     {
         requestStream.Write(data, 0, data.Length);
     }

     using (var response = request.GetResponse() as HttpWebResponse)
     using (var responseStream = response.GetResponseStream())
     using (var streamReader = new System.IO.StreamReader(responseStream, Encoding.UTF8))
     {
         return streamReader.ReadToEnd();
     }
 }

 public class Result
 {
    public string Temper { get; set; }
    public string Valence { get; set; }
    public string Arousal { get; set; }
    public string GroupP { get; set; }
    public string GroupS { get; set; }
    public string CompositeP { get; set; }
    public string CompositeS { get; set; }
 }
Posted
Comments
Richard MacCutchan 26-Jul-17 5:23am    
Look at the server logs.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900