通过formdata在react native中发送音频

时间:2018-12-07 00:53:40

标签: javascript android ios react-native audio

我正在尝试使用库here发送音频文件,并且一切正常,可以记录,停止和播放音频,但是当我尝试通过formdata发送此音频文件时,文件会损坏。

这是我的代码:

<div class="popover fade right in" role="tooltip" id="popover295848" style="top: 80px; left: 193.641px; display: block;">
    <div class="arrow" style="top: 50%;"></div>
    <h3 class="popover-title">Popover Header</h3>
    <div class="popover-content">Some content inside the popover</div> 
</div>

<div class="popover fade right in" role="tooltip" id="popover503179" style="top: 80px; left: 193.641px; display: block;">
    <div class="arrow" style="top: 50%;"></div>
    <h3 class="popover-title">Popover Header</h3>
    <div class="popover-content">Some content inside the popover</div> 
</div>

但是当文件到达时,音频文件格式会发生变化,这些是我得到的结果:

::Before

当我尝试播放音频时,格式已损坏。

预先感谢

2 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,但有了另一个库react-native-soundreact-native-audio

在项目中导入方式为:

import {AudioRecorder, AudioUtils} from 'react-native-audio';
import Sound from 'react-native-sound';

formData.append("data[file_name]", {
      uri: Platform.OS == 'android' ? 'file://' + this.state.uriAudio:this.state.uriAudio,
      name: 'test.aac',
      type: 'audio/aac'
    })

这种方式对我有用,希望您能帮助他们

答案 1 :(得分:0)

我使用了这个图书馆react-native-audio-recorder-player

您可以找到如何在文档中录音和播放

但例如;

  const _onRecord = async () => {
    const result = await audioRecorderPlayer.startRecorder();
    setRecordStatus(true); // I use for control the media player
    audioRecorderPlayer.addRecordBackListener((e) => {
      setRecordDetail({
        recordSecs: e.current_position,
        recordTime: audioRecorderPlayer.mmssss(Math.floor(e.current_position)),
      });
    });
  };

  const _onStop = async () => {
    const result = await audioRecorderPlayer.stopRecorder();
    setRecordStatus(false);
    setRecordingPath(result); // My record uri
    audioRecorderPlayer.removeRecordBackListener();
    setRecordDetail({
      ...recordDetail,
      recordSecs: 0,
    });
    console.log(result);
  };

您的记录应该像;

  formData.append('file', {
    uri:
      Platform.OS === 'android'
        ? record
        : record.replace('file://', ''),
    name: 'test.mp4',
    type: 'audio/mp4',
  });