'How to Send an Audio file (.wav) from My Flutter Application to a Flask Server Instance?
I have a machine learning model that is saved as .h5 and used in a flask server. The server is supposed to take an audio file as input and return a prediction string. My Flask server code:
@app.route("/predict", methods=["POST"])
def predict():
# get file from POST request and save it
audio_file = request.files["file"]
file_name = str(random.randint(0, 100000)) # generate file name as a dummy random number
#wav_filename = str(random.randint(0, 100000))
audio_file.save(file_name)
# instantiate keyword spotting service singleton and get prediction
kss = Keyword_Spotting_Service() # Where our model is hold
predicted_emotion = kss.predict(file_name)
# we don't need the audio file any more - let's delete it!
os.remove(file_name)
# send back result as a json file (dictionary)
result = {"emotion": predicted_emotion}
return jsonify(result)
I tested my server using python client and it worked.
in my flutter app I created a predict method:
final uri = Uri.parse('http://192.168.1.14:5000/predict');
final request = new http.MultipartRequest("POST", uri);
request.fields['audio'] = "audio";
//myStreamController.stream.asBroadcastStream().listen(request);
final multipartFile = new http.MultipartFile.fromBytes('file', (await rootBundle.load("assets/audioFile.wav")).buffer.asUint8List( ), filename: 'audioFile.wav');
request.files.add(multipartFile);
request.headers["Content-Type"] = 'multipart/form-data';
final streamedResponse = await request.send();
// final x = await streamedResponse.stream.toBytes();
Response response = await http.Response.fromStream(streamedResponse);
Map<String, dynamic> result = jsonDecode(response.body);
var resultx = jsonDecode(json.encode(response.body));
predic = "${resultx['emotion']}";
// resultx.clear();
return predic;
It keeps giving me this error: File contains data in an unknown format (Runtime Error).
What am I missing? Any help will be highly appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
