我有一个服务器上托管的音频文件,我希望我的应用程序在身份验证后访问这些文件。用户发送包含身份验证令牌的GET请求,服务器返回二进制音频数据。
据我所知,没有办法将这个'blob‘作为音频文件保存到文件系统中。react-native中当前的fetch实现不支持blobs:link
..。而理想的react-native-fetch-blob库在expo中也不受支持:link
另外,我看不到从服务器流式传输音频文件的方法。包含的audio library with expo允许来自url的音频流(例如,http://example.com/myaudio.mp3),但是我看不到任何方法来将授权头附加到请求(例如,"Authorization":“持有者my-token")。
有没有办法实现这一点,或者通过下载并保存音频blob,或者从请求中包含授权头的url流式传输?我可以将我的项目从世博会中分离出来,但我想把它作为最后的手段。
发布于 2017-11-13 20:21:55
是的,是这样的。您需要使用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;发布于 2019-10-07 09:20:18
我想通了。我应该用async把声音加载到componentdidmount。以防有人遇到这个问题
componentDidMount() {
this.loadAudio();
}
//async function to load the audio
async loadAudio() {
const { navigation } = this.props;
const id = navigation.getParam("id");
this.sound = new Audio.Sound();
for (let i = 0; i < soundArray.length; i++) {
if (soundArray[i].id === id) {
this.currentSound = soundArray[i];
console.log(this.currentSound);
break;
}
}
try {
await this.sound.loadAsync({
uri: this.currentSound.sound /* url for your audio file */
});
await this.sound.setOnPlaybackStatusUpdate(
this._updateScreenForSoundStatus
);
} catch (e) {
console.log("ERROR Loading Audio", e);
}
}https://stackoverflow.com/questions/45332922
复制相似问题