doublesymmetry / react-native-track-player

A fully fledged audio module created for music apps. Provides audio playback, external media controls, background mode and more!
https://rntp.dev/
Apache License 2.0
3.27k stars 1.01k forks source link

Question: How to play local audios from File System? #633

Closed manzoorwanijk closed 3 years ago

manzoorwanijk commented 5 years ago

Configuration

React Native Environment Info: System: OS: Windows 10 CPU: (8) x64 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz Memory: 2.85 GB / 15.86 GB Binaries: Yarn: 1.13.0 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 6.9.1-next.0 - C:\Program Files\nodejs\npm.CMD IDEs: Android Studio: Version 3.3.0.0 AI-182.5107.16.33.5314842

What react-native-track-player version are you using? 1.1.4

Question

I use react-native-fs to get the path to the local file downloaded from SoundCloud. The path resolves to /data/user/0/com.mycoolapp/files/file.mp3 on Android. Then in TrackPlayer.add, I pass this :

{
  ...
  url: { uri : Platform.OS === 'android' ? 'file://' + path :  path },
  ...
}

but it does not work.

P.S. File System permissions are already taken care of.

Guichaguri commented 5 years ago

Don't wrap it around a object, use a string directly:

{
    url: Platform.OS === 'android' ? 'file:///' + path :  path
}
manzoorwanijk commented 5 years ago

@Guichaguri I did try that as well, but it doesn't work either.

manzoorwanijk commented 5 years ago

@Guichaguri any update on this?

RayhanYulanda commented 5 years ago

Have you give permission readable on android?

manzoorwanijk commented 5 years ago

@RayhanYulanda please check the end of the question.

Guichaguri commented 5 years ago

Do have any relevant logs or errors from when you try to play the track?

manzoorwanijk commented 5 years ago

There are no errors at all. It's just that the audio doesn't play.

feedcast-me commented 4 years ago

Any solutions here? I'm having the same problem on Android

felixspitzer commented 4 years ago

Same here. If somebody figured it out, please let me know 🙏

mateus-cazuza commented 4 years ago

I am also interested in this solution.

maxckelly commented 4 years ago

I'm also interested in a solution, I have the file path but no sound plays, then I put in a URL sound and everything works fine.

felixspitzer commented 4 years ago

@MasterTeus @maxckelly for me it is working on iOS. Only problem is Android. Can you confirm?

maxckelly commented 4 years ago

@felixspitzer Mine isn't working on both iOS and Android. See below code. My file path is this below as well Also what package are you using to record your audio?

capturedAudio - "file:///Users/userName/Library/Developer/CoreSimulator/Devices/9C17B51D-FD44-4579-A1A8-FC44C7/data/Containers/Data/Application/EF9FB-E30-42FB-926F-F06E6A652E9/Library/Caches/testplay.mp4"

    const startAudio = async () => {
      // Add a track to the queue
      await TrackPlayer.add({
        id: questionID,
        url: capturedAudio,
        title: questionTitle,
        artist: questionTitle,
      });

      return playAudio();
    };
felixspitzer commented 4 years ago

@maxckelly I am downloading the file with rn-fetch-blob and passing the path to the trackObject. This is working for iOS Don't know about your mp4 and if the track-player can handle it. Haven't tested it.

const audioPath = await RNFetchBlob.config({
  fileCache: true,
  appendExt: 'mp3',
}).fetch('GET', ressourceURL)

const track = {
  ...trackInfo, // other track info like artist, id and artwork
  url: 'file://' + audioPath.data
}
maxckelly commented 4 years ago

Thanks @felixspitzer, while I haven't solved the issue we're facing you lead me in the right direction. I'm trying to access the file from the device cache. After doing RNFetchBlob.fs.readStream it returns that the file does not exist, seems like that might have something to do with audio not playing.

felixspitzer commented 4 years ago

Hi @maxckelly! I got it working with react-native-fs. Downloading the file with downloadFile and using the same path and passing it to the track-player was as easy as it could be. If you need more info, let me know.

maxckelly commented 4 years ago

Hey @felixspitzer - Would love the help. I also started using react-native-fs, how did you do it?

mateus-cazuza commented 4 years ago

🐙 Hello Guys, you can solve it, the only problem is the file patch. Android resolution: What helped me to find the real path of the file was to go to the file manager (I recommend ES File Explorer) and go to the properties of the file and copy the path where and find the .mp3 the path that Track Play accepts as a path is: file:///storage/emulated/0/Download/${nameFile}.mp3

In my case I have an array of URL Stream and I want to know if they are already downloaded, I used thern-fetch-blod to download it in the Downloads folder (android) and I used a fs.exist function to know if the path exists, if it exists play directly from the device, otherwise it will play via stream. The fs.exist(path).then((data) => {...}) function returns a boolean (true / false)

fs.exists(`file:///storage/emulated/0/Download/${cleanName}.mp3`).then(
      (data) => {
        if (data == true) {
          setDownloadStatus('success');
          setFileExist(data);
          console.log(data + ' Exist');
        } else if (data == false) {
          console.log(data + ' Not Exist');
        } else {
          console.log('Outhers');
        }
      }
    );

Some problems faced: The file name in path must not contain spaces, I initially renamed it to song.mp3 and it worked, so I treated the file name string to replace spaces with '-'.

ShumGG commented 3 years ago

@MasterTeus I did, but it doesnt work either

devpascoe commented 3 years ago

Interesting, i had an issue with a local file not playing if it had an extension of .mpga (from network was fine). Renamed during download to .mp3 and local playback worked.

Mynameisjohndev commented 1 year ago

I'm building an app to listen to local music on my device, but until now I've made a native module to help me access the music on my device, but when I try to implement the react native track player nothing happens. music does not play and no error is issued to me

Then I discovered that this library has a way of getting one song at a time through the ID, so I decided to test it, and it still didn't play in the player either. If anyone can help me I'll be here waiting.

log with local musics: image

code:

const setUpTrackPlayer = async () => {
    try {
      await TrackPlayer.setupPlayer();
      const data = await TrackPlayer.getTrack(1);
      if (data) {
        TrackPlayer.add(data);
      }
    } catch (e) {
      console.log(e);
    }
  };

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

I did it this other way here using link or require works but using file:/// no results

useEffect(() => {
    const tracks = [
      {
        id: 1,
        url: 'http://russprince.com/hobbies/files/13%20Beethoven%20-%20Fur%20Elise.mp3',
        title: 'Blues BeatBeethoven',
      },
      {
        id: 2,
        url: 'https://ia800204.us.archive.org/11/items/hamlet_0911_librivox/hamlet_act4_shakespeare.mp3',
        title: 'Shakespeare',
      },
      {
        id: 3,
        title: 'Mojnz, Emelie - Let you go',
        url: require('./src/assets/phonk.mp3'),
      },
      {
        id: 4,
        title: 'Mojnz, Emelie - Let you go',
        url: 'file:////storage/7722-13E3/Music/yung lixo - uh la la (prod biffe).mp3',
      },
    ];

    const setUpTrackPlayer = async () => {
      try {
        await TrackPlayer.setupPlayer();
        TrackPlayer.add(tracks);
      } catch (e) {
        console.log(e);
      }
    };
    setUpTrackPlayer();
  }, []);
dillonkelley commented 9 months ago

Any reason why this was closed? It seems like the issue is still there.

After upgrading react native to 0.72 and RNTP to 4.0.1 my local mp3 is not found in Android only. These settings were working prior to the upgrade

My track variable is:

export const track = {
  id: 'return-to-livestream',
  url: require('~/common/assets/track.mp3'),
  contentType: 'audio/mpeg',
  title: 'Returning to live stream...',
  artist: 'Custom',
  artwork: require('~/common/assets/img/wbez-square.png'),
  custom: {
    type: 'advertisement',
  },
};

Error Log


 E  Playback error
com.google.android.exoplayer2.ExoPlaybackException: Source error at com.google.android.exoplayer2.ExoPlayerImplInternal.handleIoException(ExoPlayerImplInternal.java:684)
...
...
Caused by: java.io.FileNotFoundException: src_common_assets_returntolivestream: open failed: ENOENT (No such file or directory) at libcore.io.IoBridge.open(IoBridge.java:575) at java.io.RandomAccessFile.<init>(RandomAccessFile.java:289) at java.io.RandomAccessFile.<init>(RandomAccessFile.java:152)