React native 将本地文件保存为本地文件

React native 将本地文件保存为本地文件,react-native,React Native,我正在使用react native、Google play music和android或ios上的其他本地音乐播放器创建本地音乐播放器通常不需要花时间在用户手机上加载音乐,我正在使用在用户手机上加载音乐,然后我会在滚动视图中显示,加载音乐需要时间,渲染音乐也需要时间,是否有一种方法可以从用户的手机中加载一次音乐,然后当应用程序重新加载时,它将不必再次加载音乐,它已经在那里了,因此应用程序只需检查是否有新音乐和旧音乐。 下面是我的代码 import React, { Component } fr

我正在使用react native、Google play music和android或ios上的其他本地音乐播放器创建本地音乐播放器通常不需要花时间在用户手机上加载音乐,我正在使用在用户手机上加载音乐,然后我会在滚动视图中显示,加载音乐需要时间,渲染音乐也需要时间,是否有一种方法可以从用户的手机中加载一次音乐,然后当应用程序重新加载时,它将不必再次加载音乐,它已经在那里了,因此应用程序只需检查是否有新音乐和旧音乐。 下面是我的代码

 import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
Image,
Dimensions,
StatusBar,
ScrollView,
View,
DeviceEventEmitter,
FlatList,
ActivityIndicator
} from 'react-native';


 import Splash from './components/Splash';
    import Home from './components/Home';
    import MusicFiles from 'react-native-get-music-files';
    import Permissions from 'react-native-permissions';
const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component{
    millisToMinutesAndSeconds(millis) {
        var minutes = Math.floor(millis / 60000);
        var seconds = ((millis % 60000) / 1000).toFixed(0);
        return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds);
      }
        componentDidMount() {
            this.setState({loaded: false});
            Permissions.request('storage').then(response => {
              this.setState({ photoPermission: response })
            })
            MusicFiles.getAll({
                id : true,
                blured : false,
                artist : true,
                duration : true, //default : true
                cover : true, //default : true,
                title : true,
                cover : true,
                batchNumber : 1, //get 5 songs per batch
                minimumSongDuration : 10000, //in miliseconds,
                fields : ['title','artwork','duration','artist','genre','lyrics','albumTitle']
            });

           }
           componentWillMount() {
            DeviceEventEmitter.addListener(
                'onBatchReceived',
                (params) => {
                    this.setState({songs : [
                        ...this.state.songs,
                        ...params.batch
                    ]}, this.setState({loaded: true}));
                }
            )

        }
    constructor(props) {
        super(props);
        this.state = {
            timePassed: false,
            photoPermission: '',
            songs: [], 
            loaded: true,
            loading: false
        };
    }
    render() {
    if (!this.state.loaded) {
        return (
            <Splash/>
           );
    } else {
        return (
            <View style={styles.linearGradient}>
            <Home songs={this.state.songs}/>
            </View>
        );

    }
    }
    }

    Home.js
    render() { 
        const lyrics = this.props.songs.map((song, index) =>
        <View style={styles.musicBox} key={index}>
        <View style={{width: 57, height: 59, borderRadius: 9, marginLeft: 15}}>
         <Image resizeMode="contain"
         style={{alignSelf: 'center', borderRadius: 9, width: 57, height: 59}}
          source={{uri: song.cover}}/>
          </View>
         <View style={styles.TextBox}>
          <Text 
          numberOfLines={1} 
          style={{fontFamily: 'nexaBold', fontSize: 20, color: 'white', flex: 1}}>
              {song.title}
          </Text>
          <View style={{flexDirection: 'row', }}>
          <Text 
          numberOfLines={1} 
          style={{fontFamily: 'nexaLight', fontSize: 10, color: '#917D7D', 
          marginRight: 5, }}>
              {song.author}
          </Text>
          <View style={{alignSelf:'center',width: 2, height: 2, borderRadius: 1, backgroundColor: '#917D7D',marginRight: 5}}>

          </View>
          <Text style={{fontFamily: 'nexaLight', fontSize: 10, color: '#917D7D'}}>
              {this.millisToMinutesAndSeconds(song.duration)}
          </Text></View>
         </View>
        </View>         
        );

        const music = 
            <ScrollView overScrollMode={'never'} keyboardShouldPersistTaps='always'>
            {lyrics}</ScrollView>;
        const shadowOpt = {
            color: "#000",
            border: 12,
            opacity: '0.08',
            radius: 12,
            x: 0,
            y: 1,
        };          
         return (
            <View style={{flex: 1}}>
            <View style={styles.linearGradient}>                                      
                {music}
                </View>
            </View>
        );
        }
import React,{Component}来自'React';
进口{
平台,
样式表,
文本,
形象,,
尺寸,
状态栏,
滚动视图,
看法
设备事件发射器,
平面列表,
活动指示器
}从“反应本机”;
从“/components/Splash”导入飞溅;
从“./components/Home”导入Home;
从“获取音乐文件”导入音乐文件;
从“反应本机权限”导入权限;
const指令=Platform.select({
ios:'按Cmd+R重新加载,\n'+
“用于开发菜单的Cmd+D或shake”,
android:“双击键盘上的R以重新加载,\n”+
'为开发菜单摇动或按下菜单按钮',
});
导出默认类应用程序扩展组件{
毫秒和秒(毫秒){
var分钟=数学地板(毫/60000);
变量秒=((毫秒%60000)/1000).toFixed(0);
返回(秒==60?(分钟+1)+“:00”:分钟+”:“+(秒<10?:”)+秒);
}
componentDidMount(){
this.setState({loaded:false});
权限。请求('存储')。然后(响应=>{
this.setState({photoPermission:response})
})
音乐档案({
id:是的,
模糊:错,
艺术家:是的,
持续时间:true,//默认值:true
cover:true,//默认值:true,
标题:对,
封面:对,
batchNumber:1,//每批获得5首歌曲
最小持续时间:10000,//以毫秒为单位,
字段:[“标题”、“艺术品”、“持续时间”、“艺术家”、“流派”、“歌词”、“专辑标题”]
});
}
组件willmount(){
DeviceEventEmitter.addListener(
“onBatchReceived”,
(参数)=>{
此.setState({歌曲:[
…这个州的歌,
…参数批处理
]},this.setState({loaded:true}));
}
)
}
建造师(道具){
超级(道具);
此.state={
时间流逝:错误,
照片许可证:“”,
歌曲:[],
是的,
加载:错误
};
}
render(){
如果(!this.state.loaded){
返回(
);
}否则{
返回(
);
}
}
}
Home.js
render(){
const歌词=this.props.songs.map((歌曲,索引)=>
{song.title}
{宋。作者}
{this.millisToMinutesAndSeconds(song.duration)}
);
康斯特音乐=
{歌词};
常数shadowOpt={
颜色:“000”,
边界:12,
不透明度:“0.08”,
半径:12,
x:0,,
y:1,,
};          
返回(
{音乐}
);
}

我用过react native获取音乐文件,速度非常慢

您可以使用和来缓存和加载文件,而不是每次用户打开应用程序时都扫描手机

编辑

获取媒体的函数。您需要先申请访问外部存储(Android)的权限

取出媒体文件后,您可以将其清理一点,然后将其发送到还原器,使其成为状态的一部分

dispatch({ type: 'get_media_success', payload: mediaAssets});
这些媒体文件将在应用程序重启之间自动保存。您只需要使用redux persist正确配置存储

My store.js文件:

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { persistStore, persistReducer } from 'redux-persist';
import { AsyncStorage } from 'react-native';
import reducers from '../Reducers';

const persistConfig = {
    key: 'root',
    storage: AsyncStorage,
    blacklist: ['search'] //Anything you don't want to persist goes here
};

const persistedReducer = persistReducer(persistConfig, reducers);

export const store = createStore(persistedReducer, {}, compose(applyMiddleware(thunk)));
export const persistor = persistStore(store);
然后导入persistor并存储和包装根组件,如下所示:

<PersistGate loading={null} persistor={persistor}>
     <Provider store={store}>
         <RootComponent/>
     </Provider>
</PersistGate>


AsyncStorageRedux Persist本身就是AsyncStorage的包装器。如果你使用普通的异步存储,那么管理这么多的文件会比较困难。请你发送链接到你使用redux persist和react-native获取音乐文件的代码,redux persist一直在给我issues@AdokiyeIruene我已经更新了我的答案。希望这对你有帮助。
<PersistGate loading={null} persistor={persistor}>
     <Provider store={store}>
         <RootComponent/>
     </Provider>
</PersistGate>