When attempting to utilize expo-av in a React-Native project on iOS, the recorded MP4 file encountered an issue when trying to submit it as form data for Open

I've been working tirelessly through the night, trying to record myself on my iPhone using expo-av to capture speech and then upload it to openai's transcriptions endpoint with the whisper-1 model.

The recording is saved as an mp4 file, which I then convert into a base64 string. I have verified that the base64 content corresponds to an mp4 format:

Tool for converting base64 to file

https://i.sstatic.net/vTXty.png

Tool for uploading and checking the file

https://i.sstatic.net/UuxTn.png

Below is the react-native code snippet:

  const recordingOptions = {
    android: {
      extension: ".mp4",
      outputFormat: Audio.AndroidOutputFormat.MPEG_4,
      audioEncoder: Audio.AndroidAudioEncoder.AAC,
      sampleRate: 44100,
      numberOfChannels: 2,
      bitRate: 128000,
    },
    ios: {
      extension: ".mp4",
      // outputFormat: Audio.IOSOutputFormat.MPEG4AAC,
      audioQuality: Audio.IOSAudioQuality.HIGH,
      sampleRate: 44100,
      numberOfChannels: 2,
      bitRate: 128000,
    },
    web: {
      mimeType: "audio/mp4",
      bitsPerSecond: 128000 * 8,
    },
  };

Current implementation:

const recordingUri = recording.getURI();
      const recordingBase64 = await ExpoFileSystem.readAsStringAsync(
        recordingUri,
        {
          encoding: ExpoFileSystem.EncodingType.Base64,
        }
      );
      const languageCode = "en"; // English
      console.log(languageCode);
      console.log(recordingBase64)

      const buffer = Buffer.from(recordingBase64, "base64")
      const blob= new Blob([buffer], { type:'audio/mp4' })
      const file = new File([blob],'test.mp4', {type:'audio/mp4'})



      const formData = new FormData();
      formData.append('file',file);
      formData.append("model", "whisper-1");

      const apiUrl = "https://api.openai.com/v1/audio/transcriptions";

      const requestOptions = {
        method: "POST",
        headers: {
          Authorization: `Bearer ${OPENAI_API_KEY}`,
        },
        body: formData,
      };

      fetch(apiUrl, requestOptions)
        .then((response) => response.json())
        .then((data) => console.log(data))
        .catch((error) => console.log(error));

However, every time I receive the following response:

{"error": {"code": null, "message": "Invalid file format. Supported formats: ['m4a', 'mp3', 'webm', 'mp4', 'mpga', 'wav', 'mpeg']", "param": null, "type": "invalid_request_error"}}

Any insights on what might be going wrong here?

Answer №1

To enhance the functionality, consider including a filename parameter within the formData.append method. You can follow this example:

formData.append('file', file, 'input.mp4');

While Whisper ideally should not depend on the file extension, it appears to be doing so at the moment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Redux Toolkit slice and TypeScript were not in agreement: it was expecting 0 arguments, but received

Recently, I encountered an issue with my slice code: const investment = createSlice({ name: 'investments', initialState, reducers: { getInvestmentsRequest(state) { state.investments.status = RequestStatuses.loading; }, } }) ...

A guide to fetching responses using the axios API in React Native using the "GET" method

Below is the code snippet that I am working with: axios({ method: "GET", url: "http://112.196.108.244:9002/api/survey/question/get-question/not-answered/?surveyId=", headers: { "content-type": "application/json& ...

Unable to call a component's method from a different component in Angular 7

How can I call the toggleSidebar() method of the SidebarComponent from the HeaderComponent using the callToggleSidebarOnToggleSidebarBtn() method? I am encountering an error that I cannot comprehend. What is the correct way to use a method of one component ...

What is the process for managing data synchronization in Redux-persist?

I developed an authorization application that writes data to AsyncStorage after a successful login. I now want to access this data through shared storage and am wondering how I can transfer or remove data synchronization with Redux-persist. ...

What is the process for obtaining a push key in Firebase?

When a user submits data to the Firebase database, I need to handle the Key generated by that action in my own function. The challenge arises when a user fills out a form and sends data to our real-time DB. This data may include optional images, and I wan ...

Updating events instantly with a single click in Angular 6: A step-by-step guide

Hello there, I am currently diving into learning Angular 6 and I have encountered a query. I want to achieve a functionality where upon clicking a button, the text on the button changes as well as the corresponding event that triggers when the button is cl ...

In Angular, set the default value of the first item in the list to be highlighted when the page loads

In my project, there are two key components: 1)contact and 2)display. The contact component is responsible for displaying a list of contacts as shown in the image below: https://i.sstatic.net/SnXFZ.png Next to the contact component, I have placed anothe ...

The error message "ReferenceError: window is not defined in Angular Universal" indicates

Currently, I'm utilizing Angular 10 and undergoing the process of incorporating SSR into my project. Upon executing the npm run serve:ssr, I encounter the following error: ReferenceError: window is not defined After conducting a search online, the r ...

Unlock the power of Angular ViewChildren to access and manipulate SVG elements efficiently

I have an SVG file loaded as an object: <object data="assets/img/states.svg" type="image/svg+xml" id="map"></object> This SVG includes a large PNG map along with several rect and text elements. <rect y="224.72084" x="644.87109" ...

Challenges encountered in the data provided by the Yelp API

I've been experimenting with the Yelp API2 and trying to work with the data it returns in PHP object format. Here's an example of what the data structure looks like: stdClass Object ( [region] => stdClass Object ( [span] => std ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

Troubleshooting Image Upload Problem with Angular, Node.js, Express, and Multer

While trying to implement the functionality of uploading an image, I have been referencing various guides like how to upload image file and display using express nodejs and NodeJS Multer is not working. However, I am facing issues with getting the image to ...

Dividing a JSON object into arrays containing keys and values within an Angular framework

I have a code snippet that involves receiving a JSON object of type Tenant from an API. I need to separate this object into keys and values within my function called tenantParser(). However, when I try to log displayedValues and displayedKeys, both show ...

Creating a ref with Typescript and styled-components: A comprehensive guide

Trying to include a ref into a React component looks like this: const Dashboard: React.FC = () => { const [headerHeight, setHeaderHeight] = useState(0); const headerRef = React.createRef<HTMLInputElement>(); useEffect(() => { // @ts ...

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

My Android studio project is running smoothly on Android 7 and 8, but unfortunately encountering issues on Android 9.0 and above

If you're experiencing issues with this project on Android versions 9 and higher, but it's working fine on Android 7 and 8, you may encounter warning messages such as: uses or overrides a deprecated API. Recompile with -Xlint:deprecation for det ...

Issue with VS2017RC: TypeScript fails to produce JavaScript files

After updating to VS 2017, I noticed that modifications made to a typescript file no longer result in the generation of any javascript code, despite receiving a message indicating "outputs generated successfully" on the lower bar. I tested this issue on t ...

What sets apart TypeScript's indexed types from function signatures?

I am curious about the distinction between indexed type and function signatures in TypeScript. type A = { _(num: number): void; }['_']; type B = { _(ten: 10): void; }['_']; let a: A = (num) => { console.log(num); }; let b: B ...

Leverage the child interface as a property interface containing a generic interface

I'm facing an issue while trying to incorporate typings in React. The concept is centered around having an enum (EBreakpoint) that correlates with each device we support. A proxy wrapper component accepts each device as a prop, and then processes the ...

React Native continues to prompt for installation of react-native-cli globally

These are the steps I followed to initialize my project: $ git clone ssh:<project> $ cd <project> $ nvm install 5.0 $ nvm use 5.0 I verified that my node version is correct: v5.0.0. $ npm install $ npm install -g react-native-cli Everything ...