Я не могу правильно использовать Audio.Sound из Expo. Я не могу приостановить или обновить статус воспроизведения - PullRequest
0 голосов
/ 23 февраля 2020

Когда я пытаюсь приостановить или обновить состояние звука Объект, созданный Audio.Sound(), ошибка указывает, что звук не загружен.

Error : Cannot complete operation because sound is not loaded.

Не знаю Не понимаю, потому что я вызвал метод из того же объекта, куда я загрузил файл и воспроизвел его.

Вот мой код:

    import React, { useState, useEffect } from "react";
    import { Feather } from "@expo/vector-icons";
    import {
      StyleSheet,
      Text,
      View,
      Button,
      FlatList,
      TouchableOpacity,
      Image
    } from "react-native";
    import { Audio } from "expo-av";

    const imageLocation = "./../assets/bibliotheque";
    const soundLocation = "./../sounds/bibliotheque";

    export default BibliothequeScreen = ({ navigation }) => {
      const [playing, setPlaying] = useState(false);
      const [soundPlaying, setSoundPlaying] = useState(false);

      const soundObject = new Audio.Sound();

      const playAudio = async (key, sound) => {
        console.log(key, playing, soundPlaying);
        try {
          if (playing) {
            await soundObject.pauseAsync();
            setPlaying(false);
          } else {
            setPlaying(true);
            await soundObject.loadAsync(
              require(soundLocation + "/Presentationpiano.mp3")
            );
            await soundObject.playAsync();
          }
        } catch (error) {
          console.log(error);
        }
      };

      return (
        <View style={styles.container}>
          <FlatList
            data={sound}
            renderItem={({ item }) => (
              <View style={styles.itemContainer}>
                <TouchableOpacity
                  onPress={
                    () => playAudio(item.key, item.soundPath)
                    // item.key == playing ? setPlaying(false) : setPlaying(item.key)
                  }
                  style={styles.item}
                >
                  <View style={{ flex: 1, flexDirection: "row" }}>
                    <View style={styles.imageContainer}>
                      <Image source={item.path} style={styles.image}></Image>
                    </View>
                    <Text style={styles.text}>{item.name}</Text>
                  </View>
                  <Feather
                    name={playing && item.key === soundPlaying ? "pause" : "play"}
                    size={35}
                    color='#3D425C'
                  ></Feather>
                </TouchableOpacity>
              </View>
            )}
          />
        </View>
      );
    };

Спасибо за вашу помощь!

1 Ответ

0 голосов
/ 21 марта 2020

Попробуйте вывести const soundObject = new Audio.Sound(); из функции BibliothequeScreen, например:

  import React, { useState, useEffect } from "react";
import { Feather } from "@expo/vector-icons";
import {
  StyleSheet,
  Text,
  View,
  Button,
  FlatList,
  TouchableOpacity,
  Image
} from "react-native";
import { Audio } from "expo-av";

const imageLocation = "./../assets/bibliotheque";
const soundLocation = "./../sounds/bibliotheque";

const soundObject = new Audio.Sound();

export default BibliothequeScreen = ({ navigation }) => {
  const [playing, setPlaying] = useState(false);
  const [soundPlaying, setSoundPlaying] = useState(false);

  const playAudio = async (key, sound) => {
    console.log(key, playing, soundPlaying);
    try {
      if (playing) {
        await soundObject.pauseAsync();
        setPlaying(false);
      } else {
        setPlaying(true);
        await soundObject.loadAsync(
          require(soundLocation + "/Presentationpiano.mp3")
        );
        await soundObject.playAsync();
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={styles.container}>
      <FlatList
        data={sound}
        renderItem={({ item }) => (
          <View style={styles.itemContainer}>
            <TouchableOpacity
              onPress={
                () => playAudio(item.key, item.soundPath)
                // item.key == playing ? setPlaying(false) : setPlaying(item.key)
              }
              style={styles.item}
            >
              <View style={{ flex: 1, flexDirection: "row" }}>
                <View style={styles.imageContainer}>
                  <Image source={item.path} style={styles.image}></Image>
                </View>
                <Text style={styles.text}>{item.name}</Text>
              </View>
              <Feather
                name={playing && item.key === soundPlaying ? "pause" : "play"}
                size={35}
                color='#3D425C'
              ></Feather>
            </TouchableOpacity>
          </View>
        )}
      />
    </View>
  );
};
...