zmxv / react-native-sound

React Native module for playing sound clips
MIT License
2.79k stars 747 forks source link

Fix ios audio duration #784

Open isilher opened 2 years ago

isilher commented 2 years ago

time

Context

While working with aac audio files I noticed the returned duration was often incorrect, shorter than the actual playtime of the audio file. This issue has also been described in #228. The included changes fix the problem for me, with the disclaimer that I have only tested this with local aac files.

The problem

The cause of the issue seems to be that the AVAudioPlayer is only taking a rough estimate of the total file duration. This may be even more off target when working with remote files that might not have completed loading when playing starts.

The proposed solution

I propose to also load the file in AVURLAsset, which allows for an option (AVURLAssetPreferPreciseDurationAndTimingKey) to be specified. This way we can force iOS to load the whole audio file, asynchronously request the duration property and only then continue initialisation.

Caveats

iamyahyaahmed commented 12 months ago

this works for me setTimeout(() => { setSoundDuration(sound?.getDuration().toFixed(0)) }, 2000);

isilher commented 11 months ago

@iamyahyaahmed setting a timeout can work, but it may still fail if a file ever takes longer than the given delay to load (2 seconds in your example). And in cases where the loading might take shorter time, you have now enforced a wait time of 2 seconds where the user needs to wait for the UI to load.