如何在react-native中创建一个基本的音乐播放器?

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

想用react-native构建一个音乐播放器,但不知道如何开始以及使用什么来创建流畅的UI

我刚刚尝试了react-native-track-player,但没有得到想要的输出。 建议我一些即时且好的方法来创建反应本机应用程序。

android react-native performance react-redux react-native-navigation
1个回答
0
投票
expo install expo-av

------------

// MusicPlayer.js
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
import { Audio } from 'expo-av';

const MusicPlayer = () => {
  const [sound, setSound] = useState(null);

  async function playSound() {
    const { sound } = await Audio.Sound.createAsync(
      require('./assets/song.mp3')
    );
    setSound(sound);
    await sound.playAsync();
  }

  async function pauseSound() {
    if (sound) {
      await sound.pauseAsync();
    }
  }

  async function stopSound() {
    if (sound) {
      await sound.stopAsync();
      await sound.unloadAsync();
      setSound(null);
    }
  }

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Music Player</Text>
      <Button title="Play" onPress={playSound} />
      <Button title="Pause" onPress={pauseSound} />
      <Button title="Stop" onPress={stopSound} />
    </View>
  );
};

export default MusicPlayer;
-------------------

// App.js
import React from 'react';
import { View, StyleSheet } from 'react-native';
import MusicPlayer from './MusicPlayer';

export default function App() {
  return (
    <View style={styles.container}>
      <MusicPlayer />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
----------------------
expo start
© www.soinside.com 2019 - 2024. All rights reserved.