React Native Expo AV - 音频未播放

时间:2021-01-01 08:46:48

标签: javascript reactjs react-native expo expo-av

我正在使用 expo-av 库实现 AudioPlayer。为了播放音频,我这样做:

import { Audio } from "expo-av";

export default function AudioPlayer() {}

AudioPlayer.playSound = async function (
  source,
  initialStatus = { shouldPlay: true },
  onPlaybackStatusUpdate = null,
  downloadFirst = true
) {
  try {
    // Create a complete sound object
    const { sound, status } = await Audio.Sound.createAsync(
      source,
      initialStatus,
      onPlaybackStatusUpdate,
      downloadFirst
    );

    console.log(status);

    // Play the sound
    await sound.playAsync();

    console.log("Sound played! Unloading from memory...");

    // We are done...
    // Unload the sound from memory
    sound.unloadAsync();
  } catch (err) {
    throw err;
  }
};

但是,出于某种原因,当我这样做时

AudioPlayer.playSound(require("../../assets/microphone-button-press.mp3"));

没有声音播放。

我做错了什么? (在 iPhone 11 专业版、iOS 14 上测试)

这是我记录的状态对象的样子:

Object {
  "didJustFinish": false,
  "durationMillis": 3120,
  "hasJustBeenInterrupted": false,
  "isBuffering": false,
  "isLoaded": true,  <---------------
  "isLooping": false,
  "isMuted": false, <------------
  "isPlaying": false,
  "pitchCorrectionQuality": "Varispeed",
  "playableDurationMillis": 3120,
  "positionMillis": 0,
  "progressUpdateIntervalMillis": 500,
  "rate": 1,
  "shouldCorrectPitch": false,
  "shouldPlay": true, <-----------------
  "uri": "file:///var/mobile/Containers/Data/Application/E249E9F5-63EE-4421-88E6-F4F52B0D99F2/Library/Caches/ExponentExperienceData/%2540victorio%252Fmy-app-name/ExponentAsset-cd2511ab9f64faf7c2c23a26c8ac58c5.mp3", <----------------
  "volume": 1, <--------------
}

1 个答案:

答案 0 :(得分:0)

在播放之前加载您的声音。

await sound.current.loadAsync(
      Sounds[audioSourceWithRequire],
    );

then await sound.current.playAsync();