是否可以下载音频文件并使用React Native Expo播放?

问题描述 投票:1回答:1

我有一个服务器托管的音频文件,我希望我的应用程序在验证后可以访问。用户发送包含认证令牌的GET请求,服务器返回二进制音频数据。

据我所知,没有办法将这个'blob'保存为文件系统的音频文件。反应原生中fetch的当前实现不支持blob:link

...并且在expo中也不支持理想的react-native-fetch-blob库:link

另外,我看不到从服务器流式传输音频文件的方法。包含的audio library with expo允许从URL(例如http://example.com/myaudio.mp3)流式传输音频,但是我看不到任何方式将授权标头附加到请求(例如“授权”:“Bearer [my-token]”)。

有没有办法实现这一点,通过下载和保存音频blob,或从请求中包含授权标头的URL流?我可以将我的项目从世博会中分离出去,但我想把它作为最后的手段。

authentication react-native api-design fetch-api expo
1个回答
4
投票

是的。您需要使用expo公开的Audio模块来完成它。以下是从给定URL加载和播放音频文件时必须遵循的步骤。我也复制了我的组件的代码,我也这样做。

  • 加载由expo公开的音频模块 import { Audio } from 'expo'
  • 从中创建一个新的声音对象 soundObject = new Audio.Sound()
  • 异步加载文件 await this.soundObject.loadAsync({ uri: this.props.source })
  • 加载后播放加载的文件 this.soundObject.playAsync()

下面是我写的一个简单的组件 -

import React, { Component } from 'react';
import { View, TouchableNativeFeedback } from 'react-native';
import { Audio } from 'expo';

class AudioPlayer extends Component {
  constructor(props) {
    super(props);
    this.state = { isPlaying: false };

    this.loadAudio = this.loadAudio.bind(this);
    this.toggleAudioPlayback = this.toggleAudioPlayback.bind(this);
  }

  componentDidMount() {
    this.loadAudio();
  }

  componentWillUnmount() {
    this.soundObject.stopAsync();
  }

  async loadAudio() {
    this.soundObject = new Audio.Sound();
    try {
      await this.soundObject.loadAsync({ uri: this.props.source /* url for your audio file */ });
    } catch (e) {
      console.log('ERROR Loading Audio', e);
    }
  }

  toggleAudioPlayback() {
    this.setState({
      isPlaying: !this.state.isPlaying,
    }, () => (this.state.isPlaying
      ? this.soundObject.playAsync()
      : this.soundObject.stopAsync()));
  }

  render() {
    return (
      <TouchableNativeFeedback onPress={this.toggleAudioPlayback}>
        <View style={this.props.style}>
          {this.props.children}
        </View>
      </TouchableNativeFeedback>
    );
  }
}

export default AudioPlayer;
© www.soinside.com 2019 - 2024. All rights reserved.