when I use react-native-track-player, can't play audio

916 views Asked by At
import React, {useEffect, useState} from 'react';
import TrackPlayer, {usePlaybackState} from 'react-native-track-player';
import IconButton from './IconButton';

function Player({url}) {
  const [iconName, setIconName] = useState('play-circle');
  const playbackState = usePlaybackState();

  useEffect(() => {
    setup();
  }, []);

  async function setup() {
    await TrackPlayer.setupPlayer({});
    await TrackPlayer.reset();

    await TrackPlayer.add({
      id: 'trackId',
      url: url,
      title: 'Example Track',
      artist: 'Example Artist',
    });
  }

  async function togglePlayback() {
    const currentTrack = await TrackPlayer.getActiveTrackIndex();
    if (currentTrack == null) {
      await setup();
    } else {
      console.log(playbackState, TrackPlayer.STATE_PLAYING);
      if (playbackState === TrackPlayer.STATE_PLAYING) {
        await TrackPlayer.pause();
        setIconName('play-circle');
      } else {
        await TrackPlayer.play();
        setIconName('pause-circle');
      }
    }
  }

  return (
    <IconButton
      pressEvent={togglePlayback}
      name={iconName}
      size={20}
      color="rgb(166, 166, 166)"
    />
  );
}

export default Player;

I passed a music link http://music.wufazhuce.com/FkX6nZfSWVRRGacxHWGSZ2-SpjtP to Player, The link is no problem, but here is an error,error: {message: "Source error", code: "android-io-file-not-found"}, It's very strange, I don't know why can't find this file and how to solve it, please help me.

I want to play the audio after I click the button

2

There are 2 answers

0
ashisrai_ On

Use TrackPlayer.getCurrentTrack() or something else that would make sense instead of TrackPlayer.getActiveTrackIndex() and use State.Playing instead of TrackPlayer.STATE_PLAYING.

I don't think TrackPlayer has getActiveTrackIndex() and STATE_PLAYING available.

Go through the documentation Player or run console.log(TrackPlayer) to list available methods.

Visit documentation State to see types of media state made available through State.

Hope this helps. I am using ^3.2.0.

0
Ratna Sai Kumar On

i think you are trying to call the setup before having the url try to add the url in dependencys of useEffect so when your component intialzes first it will call all the useEffect and url will be null at that point of time so may be might be trowing that error