React-native-sound: How to play sound from network?

Created on 4 Jul 2017  路  5Comments  路  Source: zmxv/react-native-sound

Hi everyone,
I would like to know how to play a sound from a given url

I'm trying to run the following method which runs a local file and it also doesn't work
```
var whoosh = new Sound('advertising.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
// loaded successfully
console.log('duration in seconds: ' + whoosh.getDuration() + 'number of channels: ' + whoosh.getNumberOfChannels());
});

function onPlaySound() {
console.log('Sound started playing!');
whoosh.play((success) => {
if (success) {
console.log('successfully finished playing');
} else {
console.log('playback failed due to audio decoding errors');
}
});
}
````

Would be grateful if someone could provide me with an example of how to run an mp3 from a url

documentation

Most helpful comment

Try this, inside your component

  _loadAudio = () => {
    const sound = new Sound(
      'https://s3.amazonaws.com/hanselminutes/hanselminutes_0001.mp3',
      undefined,
      (error) => {
        if (error) {
          console.log(error);
        } else {
          console.log('Playing sound');
          sound.play(() => {
            sound.release();
          });
        }
      }
    );
  };

  _componentDidMount = () => {
    this._loadAudio();
  };

All 5 comments

Android acquiescence can, ios seems to be being error

You must wait until the sound is loaded. The best way I found was to start playing in the oncomplete handler:

    const sound = new Sound('https://s3.amazonaws.com/hanselminutes/hanselminutes_0001.mp3',
      undefined,
      error => {
        if (error) {
          console.log(error)
        } else {
          console.log("Playing sound");
          sound.play(() => {
            // Release when it's done so we're not using up resources
            sound.release();
          });
        }
      });
  }

@daramasala
I'm trying to run the following method and it also doesn't work, anyone help me?
componentDidMount() {
this._loadAudio();
}
_loadAudio(){
const sound = new Sound('https://s3.amazonaws.com/hanselminutes/hanselminutes_0001.mp3', undefined, error=>{
if (error) {
console.log(error);
}else{
console.log("Playing sound");
sound.play(()=>{
sound.release();
})
}
})

Try this, inside your component

  _loadAudio = () => {
    const sound = new Sound(
      'https://s3.amazonaws.com/hanselminutes/hanselminutes_0001.mp3',
      undefined,
      (error) => {
        if (error) {
          console.log(error);
        } else {
          console.log('Playing sound');
          sound.play(() => {
            sound.release();
          });
        }
      }
    );
  };

  _componentDidMount = () => {
    this._loadAudio();
  };

Is it possible to load sound from a network with headers for authentication to access that site?

Was this page helpful?
0 / 5 - 0 ratings