I am trying to build a web app on django where a user can record something which then gets turned into text and after that sent to the server with AJAX. I did some research and found this article: https://medium.com/@manask322/implementing-speech-to-text-feature-in-a-django-app-f0fa53bb3e03
So I copied the html code: (this is only the part I copied)
<div id='result'>
Your text will appear here
</div>
<br>
<div id= 'record'>
<button onclick="startConverting()" class='btn btn-info btn-sm' id="re">record</button>
<button class='btn btn-info btn-sm ml-3' value="Send" id="send">Send</button>
</div>
<script>
function startConverting()
{
document.getElementById("re").style.visibility = "hidden";
var r=document.getElementById('result');
var spr=new webkitSpeechRecognition(); //Initialisation of web Kit
spr.continuous=false; //True if continous conversion is needed, false to stop transalation when paused
spr.interimResults=true;
spr.lang='en-IN'; // Set Input language
spr.start(); //Start Recording the voice
var ftr='';
spr.onresult=function(event){
var interimTranscripts='';
for(var i=event.resultIndex;i<event.results.length;i++)
{
var transcript=event.results[i][0].transcript;
transcript.replace("n","<br>")
if(event.results[i].isFinal){
ftr+=transcript;
}
else
interimTranscripts+=transcript;
}
r.innerHTML=ftr +interimTranscripts ;
};
spr.onerror=function(event){};
}
$(document).ready(function() {
$("#send").click(function(event){
$.ajax({
type:"POST",
url:"/audio_data",
data: {
send : $('#result').html()
},
});
});
});
</script>
</div>
But changed the function in views.py a bit:
@csrf_exempt
def audio_data(request):
if request.method == 'POST':
result = request.POST['send']
return render(request, 'success.html')
elif request.method == 'GET':
return render(request, 'afterContinue.html')
The recording works and it also displays the text you say but when you click on send nothing happens. Does someone know why?
UPDATE: This is the urls.py part:
urlpatterns = [
path("", views.index, name="index"),
path('admin/', admin.site.urls),
path('audio_data', views.audio_data)
]
Advertisement
Answer
You can try this:
Add the jQuery CDN minified inside the <head> tag in html template:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
<div id="result">
.......
</div>
</body>
</html>
Html template
- send a parameter
savetoaudio_dataview so that it could recognise that it has to save the audio text. - send the ajax request data in json format.
- Check the response sent by django view was true or not.
- redirect the user to
/audio_data?success=trueif the response from view was true.
$(document).ready(function() {
$("#send").click(function(event){
$.ajax({
url: "/audio_data",
data: {
'save': true, // Change No.1
'text': $('#result').html()
},
dataType: 'JSON', // Change No.2
success: function(response) { // Change No.3
if (response.ans) { // Change No.3
location.href = '/audio_data?success=true'; // Change No.4
}
}
});
});
});
views.py
- Check if the save parameter is true or not.
- Check if audio text is provided or not.
- Return a
JsonResponsewith a dictionary that holds the value ofansvariable that isTrueif the audio text is saved & isFalseif the text is nor provided. - Render the
success.htmltemplate if thesuccessparameter istrue. - If both
saveandsuccessparameters areFalseor not provided then renderafterContinue.htmltemplate.
from django.http import JsonResponse
@csrf_exempt
def audio_data(request):
data = request.GET
if data.get('save', False): # Change No.5
ans = True
text = data.get('text', False) # Change No.6
if text: // Change No.6
print('Text = ', text)
""" Here save the text the way you want. """
else:
ans = False
return JsonResponse({'ans':ans}) # Change No.7
elif data.get('success', False): # Change No.8
return render(request, 'success.html')
return render(request, 'afterContinue.html') # Change No.9