Playing an audio file with source => {uri: 'remote-file-path'} not working - React Native (expo) - react-native

I keep getting this error when i try to play an audio from my local backend or an already uploaded audio from a site.
No matter what file format, this is what I get and this only happens with ios
error: Possible Unhandled Promise Rejection (id: 0): Error: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain". Error: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain".
error image
const player = new Audio.Sound();
player.loadAsync({ uri: url }, initialStatus).then(() => {
player.playAsync().then((playbackStatus) => {
if (playbackStatus.error) {
handlePlaybackError(playbackStatus.error);
}
});
});
After adding more error handling, I found out the error comes from loadAsync and it only happens when I try to play an audio from my local backend server. (ex: http://127.0.0.1:8000/media/audios/2021/08/08/27/21/filename.mp4)
It would be really great if I could get help on this, thanks in advance!
Update: Provided more code

So I found out that the that warning was being generated and preventing my audio files from playing because they are stored in my local server and for some reason the expo Audio.Sound object had an issue loading them, so I had to install expo-file-system, use the FileSystem to read download the file and use the uri produced from the download.
Example:
import * as FileSystem from 'expo-file-system';
const splitUrl = url.split('/');
const lastItem = splitUrl[splitUrl.length - 1];
const { uri } = await FileSystem.downloadAsync(
url,
FileSystem.documentDirectory + lastItem
);
const source = { uri: uri }; //the source you provide to the loadAsync() method

loadAsync() returns a Promise, so you have to await it.
If this is not the problem you have to provide more code, please.
Here's the documentation, so use it like this:
const sound = new Audio.Sound();
try {
await sound.loadAsync(require('./assets/sounds/hello.mp3'));
await sound.playAsync();
// Your sound is playing!
// Don't forget to unload the sound from memory
// when you are done using the Sound object
await sound.unloadAsync();
} catch (error) {
// An error occurred!
}
And here's a simple snack I made, it works for me, you might want to consider error handling using try-catch:
Snack example

Related

Storage.put() throwing - AWSS3Provider - error uploading TypeError: Cannot read property 'byteLength' of undefined

JavaScript Framework (Vue)
Amplify APIs (Storage)
Amplify Categories (storage)
Getting Cannot read property 'byteLength' of undefined while uploading media to s3 bucket using amplify storage, below is the code I am currently using
async onUpload(fileArr) {
if (fileArr.length > 0) {
console.log("fileArr", fileArr);
fileArr.map(async (obj) => {
try {
console.log({ Storage, Amplify });
console.log("Object =>", obj);
let baseData = await this.toBase64(obj);
console.log("Base Data =>", baseData);
const arrayBuffer = decode(baseData);
console.log("Array buffer =>", arrayBuffer);
let result = await Storage.put(
`hub/${obj.name}`,
arrayBuffer,
{
contentType: obj.type,
}
);
console.log("S3 Upload Result =>", result);
} catch (err) {
console.log("Error in uploading", err);
}
});
}
},
I tried to convert media to base64 before uploading but still getting same error
ERROR OUTPUT
Error - AWSS3Provider - error uploading TypeError: Cannot read property 'byteLength' of undefined
I granted full access to my IAM user and role but it didn't work either, I looked for multiple solution available online but still I didn't make it out.
I also faced this problem while uploading data to s3 using Apmplify.
The problem is not in your code its library version issue, make sure to use same Amplify version which is used on server
Latest Amplify version is 4.3.0
https://www.npmjs.com/package/aws-amplify

React Native fetch fail

When I use fetch() method to make get request, it failed with "TypeError: Network request failed". It's weird that it sometimes failed but sometimes succeeded. I have tried the solution here: React Native fetch() Network Request Failed, but it didn't work for me. By the way, I am using Android.
This is my code :
try {
let url = "http://140.116.245.229:3000/GetCarsJson";
let data = await fetch(url);
let toJson = await data.json();
} catch(err) {
throw err;
}
This is the error message :
enter image description here
You should ensure your devices/simulator/emulator can connect to this endpoint
If you use Android emulator, you can refer this link How to connect to a local server from an android emulator?

React Native: Network error when using axios on local server

I'm new to react-native, I want to fetch some data from my local laravel server, but I fire the mobx action I get the following errors:
Network Error
[Unhandled promise rejection: Error: Network Error]
This is my mobx action (I'm using flow, similar to async/await), I get 'fire' log but after that I get the error above:
listProducts = flow( function*(payload)
{
console.log('fire');
try
{
let response = yield axios.get('http://192.168.1.39:8000/api/products', { params: payload });
this.posts = response.data;
this.pagination = response.data.pagination;
console.log(response);
//return response;
}
catch (error)
{
console.error(error);
throw error;
}
});
As you can see I'm using my local IP instead of localhost, I'm also testing my app on my android device using EXPO connected to the same network as my dev laptop.
Ciao, I can't see errors on your code. Try to follow this guide to handle Unhandled promise rejection. Could help you to find a clue.
In brief the guide suggest to use axios interceptors:
axios.interceptors.response.use(
response => response,
error => {}
)

React Native with axios - Network error calling localhost with self signed https endpoint

I created service in Visual Studio with Conveyor extension to make it accessible in local network. I installed certificate on my Android device so there is green padlock when calling it in browser and service works fine.
However when calling it from React Native app with axios then i get Network error.
That's my code:
const fetchData = async () => {
console.log('url', `${Settings.API_URL}/location/GetDataByMyIp`);
try {
const result = await axios(
`${Settings.API_URL}/location/GetDataByMyIp`,
);
console.log('result', result);
ipData = {
city: result.data.city,
longitude: result.data.longitude,
latitude: result.data.latitude,
};
} catch (e) {
console.log('error', e);
}
};
await fetchData();
In console i see:
url https://192.168.1.14:45455/api/location/GetDataByMyIp
error Error: Network Error
at createError (path_to_app\node_modules\axios\lib\core\createError.js:16)
at EventTarget.handleError (path_to_app\node_modules\axios\lib\adapters\xhr.js:83)
at EventTarget.dispatchEvent (path_to_app\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575)
at EventTarget.__didCompleteResponse (path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at path_to_app\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (path_to_app\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
at MessageQueue.__guard (path_to_app\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373)
I tried to add this line to AndroidManifest.xml application tag but still have the error
android:usesCleartextTraffic="true"
Some solutions say about adding as 2nd parameter to axios, but it doesn't work with React Native.
new https.Agent({
rejectUnauthorized: false,
});
I tried to call some other service from the internet and then error was gone.
Is there some solution to this? I haven't found anything more. My last idea is to host service on Azure so I'll have properly signed SSL, but i guess it has to be a way to run it locally.
Edit: It works through http

Use require('../assets/file.mp3') in ES6

I am trying to load a local mp3 file to be played using Expo Audio SDK.
Here's an example from the documentation:
const soundObject = new Audio.Sound();
try {
await soundObject.loadAsync(require('./assets/sounds/hello.mp3'));
await soundObject.playAsync();
// Your sound is playing!
} catch (error) {
// An error occurred!
}
I am also using ES6 in my project which makes require unavailable.
Is there any way I could still load a local resource in ES6?
As far as I know, require is still a thing in ES6. I've used it plenty of times throughout my apps. The example should work, have you tried it?