我有一个服务器托管的音频文件,我希望我的应用程序在验证后可以访问。用户发送包含认证令牌的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流?我可以将我的项目从世博会中分离出去,但我想把它作为最后的手段。
是的。您需要使用expo公开的Audio模块来完成它。以下是从给定URL加载和播放音频文件时必须遵循的步骤。我也复制了我的组件的代码,我也这样做。
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;