2

我是反应/反应本机的新手,并试图构建一个播放本地 MP3 的简单应用程序。我正在使用 react-native-sound 模块,它似乎工作得很好。

虽然现在,我正在尝试将fileName我的类别中的道具作为道具传递给播放器组件。似乎 react-native-sound 需要我预加载一个声音文件。因此,现在我收到以下错误:

“未处理的 JS 异常:无法读取未定义的属性 'fileName'”。

...    
import Sound from 'react-native-sound';

const play = new Sound(this.props.fileName, Sound.MAIN_BUNDLE, (error) => {
  if (error) {
    console.log('failed to load the sound', error);
  } else { // loaded successfully
    console.log('duration in seconds: ' + play.getDuration() +
        'number of channels: ' + play.getNumberOfChannels());
  }
});

export default class playTrack extends Component {
    constructor(props) {
      super(props);
      this.state = {
        playing: false,
        track: this.props.fileName,
      };
    }

    playTrack() {
      this.setState({playing: true})
      play.play((success) => {
        if (success) {
          console.log('successfully finished playing');
        } else {
          console.log('playback failed due to audio decoding errors');
        }
      })
    }
...

你对我有什么建议吗?

4

1 回答 1

2

您无法以this尝试使用它的方式从类外部访问您的类实例。相反,Sound在构造函数中创建:

import Sound from 'react-native-sound';

export default class playTrack extends Component {
    constructor(props) {
        super(props);

        this.play = new Sound(props.fileName, Sound.MAIN_BUNDLE, (error) = > {
            if (error) {
                console.log('failed to load the sound', error);
            } else { // loaded successfully
                console.log('duration in seconds: ' + this.play.getDuration() +
                    'number of channels: ' + this.play.getNumberOfChannels());
            }
        });

        this.state = {
            playing: false,
            track: this.props.fileName,
        };
    }

    playTrack() {
        this.setState({
            playing: true
        })
        this.play.play((success) = > {
            if (success) {
                console.log('successfully finished playing');
            } else {
                console.log('playback failed due to audio decoding errors');
            }
        })
    }
于 2016-11-16T15:28:01.453 回答