Hier ist ein Beispiel mit Recorder.js. Zuerst erstellst du in deiner Flask App eine Methode zum Hochladen von Dateien.
@app.route('/upload', methods=['POST'])
def upload():
if 'audio' not in request.files:
return redirect(url_for('index'))
print( "trying..")
audio_file = request.files['audio']
if audio_file:
filename = 'uploads/recording.wav'
audio_file.save(filename)
return 'Upload erfolgreich!'
und das HTML Template dazu speicherst du im Ordner "templates".
<html>
<head>
<title>Audioclip aufnehmen und hochladen</title>
<script src="https://cdn.rawgit.com/mattdiamond/Recorderjs/08e7abd9/dist/recorder.js"></script>
</head>
<body>
<h1>Audioclip aufnehmen und hochladen</h1>
<button id="startRecord">Aufnahme starten</button>
<button id="stopRecord" disabled>Aufnahme stoppen</button>
<audio controls id="audioPlayer" style="display: none;"></audio>
<form action="/upload" method="POST" enctype="multipart/form-data" style="display: none;">
<input type="file" name="audio" id="audioInput" accept="audio/*">
<input type="submit" value="Hochladen">
</form>
<script>
var startButton = document.getElementById('startRecord');
var stopButton = document.getElementById('stopRecord');
var audioPlayer = document.getElementById('audioPlayer');
var audioInput = document.getElementById('audioInput');
var recorder;
startButton.addEventListener('click', function () {
startButton.disabled = true;
stopButton.disabled = false;
var audioContext = new (window.AudioContext || window.webkitAudioContext)();
navigator.mediaDevices.getUserMedia({ audio: true }).then(function (stream) {
var input = audioContext.createMediaStreamSource(stream);
recorder = new Recorder(input);
recorder.record();
document.getElementById("status").innerHTML = "Starting recording..";
}).catch(function (error) {
console.error('Error accessing microphone:', error);
document.getElementById("status").innerHTML = "Error while recording..";
});
});
stopButton.addEventListener('click', function () {
stopButton.disabled = true;
startButton.disabled = false;
recorder.stop();
recorder.exportWAV(function (blob) {
audioPlayer.src = URL.createObjectURL(blob);
audioPlayer.style.display = 'block';
audioInput.style.display = 'none';
var form = new FormData();
form.append('audio', blob, 'recording.wav');
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('Upload successful');
}
};
xhr.send(form);
});
recorder.clear();
});
</script>
</body>
</html>