iOS can't play uploaded audio: JS MediaRecorder -> Blob -> Django Server -> AWS s3 -> JS decodeAudioData --> "EncodingError: Decoding Failed" - django

Answer: shouldn't set content/mime type browser side with JS, should use native browser mimeType then convert server side (I used PyDub).
Question:
I am using Javascript MediaRecorder, Django, AWS s3 and Javascript Web Audio API to record audio files for users to share voice notes with one another. I've seen disbursed answers online about how to record and upload audio data and the issues with Safari/iOS but thought this could be a thread to bring it together and confront some of these issues.
Javascript:
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.onstop = function (e) {
var blob = new Blob(
chunks,
{
type:"audio/mp3",
}
);
var formdata = new FormData();
formdata.append('recording', blob)
var resp = await fetch(url, { // Your POST endpoint
method: 'POST',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': csrf_token,
},
body: formdata,
})
}
Django:
for k,file in request.FILES.items():
sub_path = "recordings/audio.mp3"
meta_data = {"ContentType":"audio/mp3"}
s3.upload_fileobj(file, S3_BUCKET_NAME, sub_path,ExtraArgs=meta_data)
###then some code to save the s3 URL to my database for future retrieval
Javascript:
var audio_context = new AudioContext();
document.addEventListener("#play-audio","click", function(e) {
var url = "https://docplat-bucket.s3.eu-west-3.amazonaws.com/recordings/audio.mp3"
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function () {
audio_context.decodeAudioData(request.response, function (buffer) {
playSound(buffer)
});
}
request.send();
})
Results in:
"EncodingError: Decoding Failed"
Note however that using the w3 schools demo mp3 url does play the recording:
https://docplat-bucket.s3.eu-west-3.amazonaws.com/recordings/t-rex-roar.mp3
Specs:
PC (used to upload recoding): Windows 11, Chrome Version 98.0.4758.81 (Official Build) (64-bit)
Django: Version: 3.1.7
Mobile (used to play recording): iPhone X, iOS (Version 14.7.1)
Problematic url: https://docplat-bucket.s3.eu-west-3.amazonaws.com/recordings/audio.mp3
Working url: https://docplat-bucket.s3.eu-west-3.amazonaws.com/recordings/t-rex-roar.mp3
(This is my first post so please forgive me if I haven't asked this question in the ideal way :) )

When you upload the recorded Blob you set the type to 'audio/mp3'. But unless you use a custom library which patches the MediaRecorder the mimeType of the recording will be whatever the browser likes best.
As of now it's 'audio/opus' in Firefox and 'audio/webm' in Chrome.
If you define your Blob like this it should work.
var blob = new Blob(
chunks,
{
type: mediaRecorder.mimeType
}
);
You would also have to change your server side code to not use 'audio/mp3' anymore.

Related

S3 - Video, uploaded with getSignedUrl link, does not play and is downloaded in wrong format

I am using AWS SDK in Server Side with Node.JS and having issue with uploading files as formData from client side.
On the server side I have simple route, which creates upload link, where video will be uploaded later directly from client side.
I am using S3 getSignedUrl method for generating that link with putObject, which creates PUT request for client, but causes very strange issue with formData.
Video uploaded as formData is not behaving correctly - instead of playing it S3 uploaded url downloads that video and it is also broken.
Here is simple how i configure that method on server side:
this.s3.getSignedUrl(
'putObject',
{
Bucket: '<BUCKET_NAME>',
ContentType: `${contentType}` -> video/mp4 as a rule,
Key: key,
},
(err, url) => {
if (err) {
reject(err)
} else {
resolve(url)
}
},
)
axios put request with blob is actually working, but not for formData.
axios.put(url, file, {
headers: {
'Content-Type': file.type,
},
onUploadProgress: ({ total, loaded }) => {
setProgress((loaded / total) * 100)
},
})
This is working version, but when I try to add file to formData, it is uploaded to S3, but video downloads instead of playing.
I do not have big experience in AWS, so if somebody knows how to handle that issue, I will be thankfull

Cannot upload file from React Native: "Network request failed"?

When trying to upload a selected image from my React Native project I get a nondescript error message:
Network request failed
Seems to be a common issue, but most people are just forgetting their file types or are on Android and have an issue with Flipper. Nothing that has worked for anyone I've found with the same symptoms has worked for me.
Code:
const localUri = result.uri;
const filename = localUri.split("/").pop();
const type = mime.lookup(localUri) || "image";
const formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
try {
const file = await fetch(`${SERVER_URL}/api/upload`, {
method: "POST",
body: formData,
}).then((res) => {
console.log(res);
return res.status === 200 ? res.text() : res.json();
});
} catch (e) {
console.log(e);
}
Considerations:
Using a physical IOS device. Iphone.
Using Expo 40.0.0 with corresponding RN SDK, not ejected.
Using expo-image-picker to get image.
Using NGROK to get requests through to my localhost server from my phone.
All other requests to my server from React Native work fine, it's only when I try to uplaod a file
Image renders fine from supplied URI, so it's getting the right source.
Form Data source from above:
{ "name": "CAPS-FILE-NAME.jpg", "type": "image/jpeg", "uri": "file:///var/mobile/Containers/Data/Application/CAPS-PATHING/Library/Caches/ExponentExperienceData/project-src-pathing/ImagePicker/CAPS-FILE-NAME.jpg", }
Things tried:
Using Content-Type header: "multipart/form-data"
Using /private instead of file://
Using Postman to hit my server through NGROK, which works
Changing my Expo/RN to 38.0.0
Getting base64 -> blob -> formData, same result
Many other things I've forgotten now. If it's on Google results, I've tried it.
For anyone who gets stuck with this also, I switched to using XMLHttpRequest instead of fetch and it miraculously works now. Not sure why fetch is broken in RN, but at least there's a solution.

Trouble getting my Chrome extension to get data from Amazon RDS

I have a Chrome extension. It uses a background.js script to post and get data with a python website that talks to a Mariadb (similar to MySQL) database. It all worked well locally.
Then I moved the python to Elastic Beanstalk and the database to RDS. The AWS website and the database work fine, but the extension has a problem. The extension posts data to RDS just fine, but I get an error when I try to get data: flask-env.ivkkarzmwt.us-east-2.elasticbeanstalk.com93’s server IP address could not be found.The background.js console just says GET 500: Internal Server error.
Here's the background.js:
fetch('http://flask-env.ivkhmrzmwt.us-east-2.elasticbeanstalk.com/bootstrap')
.then(function (response) {
return response.text();
}).then(function (text) {
console.log('GET response text:');
// console.log(text); // Print the greeting as text
});
// Send the same request
fetch('http://flask-env.ivkhmrzmwt.us-east-2.elasticbeanstalk.com/bootstrap')
.then(function (response) {
return response.json(); // But parse it as JSON this time
})
.then(function (json) {
console.log('GET response as JSON:');
console.log(json); // Here’s our JSON object
console.log ("here's the sun");
console.log (json.greeting)
var integer = parseInt(json.greeting, 10);
console.log(integer + 1)
})
$.ajax({
type: 'POST',
url: 'http://flask-env.ivkhmrzmwt.us-east-2.elasticbeanstalk.com/bootstrap',
data: articleData,
success: function myFunction(data) {
integer = data;
var myInput = integer
var websitelink = "http://flask-env.ivkhmrzmwt.us-east-2.elasticbeanstalk.com" + myInput;
window.open(websitelink, "MsgWindow", "width=400,height=500");
}

Save image picked from ReactNative/Expo ImagePicker to Baqend

I'm having a hard time saving an image that is being picked from Expo (React Native).
https://docs.expo.io/versions/latest/sdk/imagepicker.html
It seems that React Native does not have support for uploading the selected image as blob, but does have a base64 option.
The code:
_pickImage = async () => {
let pickerResult = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
base64: true,
aspect: [4, 4],
});
this._handleImagePicked(pickerResult);
};
_handleImagePicked(pickerResult) {
const uri = pickerResult.base64;
const img = new db.File({ name: 'test.jpg', data: uri, type: 'base64', mimeType: 'image/jpg' });
db.UserData.load(this.state.UserDataID).then(UserData => {
img.upload({ force: true }).then((file) => {
UserData.photo = "https://remarkable-apple-95.app.baqend.com/v1" + file.id;
alert(file.id)
return UserData.update();
},
(error) => { alert(error); }
);
});
}
When I console.log(pickerResult.base64) I get a super long string that looks like base64, but when this is run, the img.upload is throwing the error and it says "PersistentError: An unexpected persistent error occurred."
You're right. React Native has no support for binary data. Unfortunately Baqend does not support base64 file uploads yet.
As a workaround you have 2 options:
Use the React Native Fetch Blob library, which bypasses the limitations of React Native not supporting binary files by uploading and downloading the files directly via native code and gives back a reference to those. Your code could look similar to this:
ImagePicker.showImagePicker(options, async (response) => {
const upload = new db.message.UploadFile('files', 'uploadFetchBlob.jpg')
const body = 'RNFetchBlob-' + response.uri;
RNFetchBlob.fetch('PUT', 'https://{YOUR-APP-NAME}.app.baqend.com/v1' + upload.request.path, upload.request.headers, body).then((res) => {
db.File({ parent: 'files', name: 'uploadFetchBlob.jpg'}).url
})
});
Unfortunately this wont work with the expo client right now, but you'd have to eject your project and use 'native code'.
The second option would be not to use the baqend file endpoint directly, but upload your base64 string to a baqend module instead. There you can parse your base64 string and upload it to your files from within your backend module. You can find an example for this in our Guide. https://www.baqend.com/guide/topics/baqend-code/#handling-binary-data
Hope this helps

Does the Glip chat API support image (photo) attachments?

I'm using the Glip API to post messages. I can post images from the Glip UI but I don't see an option to post images. Does anyone know how to do this?
Glip API: https://developer.ringcentral.com/api-docs/latest/index.html#!#RefGlipCreatePost
Glip recently launched the file upload API which can be used to attach images. You could also try it out using our API Explorer.
In case someone comes across this looking for a working example, here's what I did (using Node and the RingCentral SDK):
var RC = require('ringcentral');
var fs = require('fs');
var FormData = require('form-data');
// {login to Glip and generate the platform object (https://github.com/ringcentral/ringcentral-js)}
var formData = new FormData();
formData.append('attachment', fs.createReadStream('image.png'));
platform
.send({
method: 'POST',
url: '/glip/files',
body: formData,
query: {
groupId: '1234', // whatever group you want to post to
}
})
.then(function(){
console.log('file uploaded');
})
.catch(function(e){
console.log(e.message);
});