【问题标题】:Play sound in iOS device in react-native以 react-native 在 iOS 设备中播放声音
【发布时间】:2019-11-20 09:02:24
【问题描述】:

在我的应用中,我有一个功能可以在收到消息时播放声音,它会通过播放声音文件来通知用户,该应用在 Android 中使用 react-native-sound 可以正常工作,但是在 iOS 中,我不断收到此错误:

我用于初始化声音的代码:

import Sound from "react-native-sound"

// Load the sound file 'whoosh.mp3' from the app bundle
// See notes below about preloading sounds within initialization code below.
var message_received = new Sound(require("../../res/audio/Page_Turn.mp3"), Sound.MAIN_BUNDLE, (error) => {
    if (error) {
      console.log('failed to load the sound', error);
      return;
    }
    // loaded successfully
    console.log('duration in seconds: ' + message_received.getDuration() + 'number of channels: ' + message_received.getNumberOfChannels());
});

初始化声音文件后调用的方法:

message_received.play()

有人知道怎么解决吗?

【问题讨论】:

  • 来自 react-native-sound 文档:iOS:打开 Xcode 并将您的声音文件添加到项目中(右键单击项目并选择将文件添加到 [PROJECTNAME])。然后你可以像 new Sound('Page_Turn.mp3',
  • 我这样做了,但仍然遇到同样的错误。
  • 执行 .play() 或初始化声音时出现错误?
  • @llario 您的解决方案有效,谢谢!
  • 太棒了!请问你能接受我的回答吗? :)

标签: javascript ios react-native react-native-sound


【解决方案1】:
  1. 如果使用require(filepath),则不需要Sound.MAIN_BUNDLE,第二个参数是回调:

    new Sound(require("../../res/audio/Page_Turn.mp3"), (error) => {})

  2. 初始化成功后应该调用play函数

    var message_received = new Sound(require("../../res/audio/Page_Turn.mp3"), (error) => { 如果(错误){ console.log('加载声音失败', error); 返回; } // 加载成功 message_received.play() });

  3. 记得将你的 .mp3 文件添加(引用)到 xcode 中,重新运行 react-native run-ios

此代码示例包含许多用例:https://github.com/zmxv/react-native-sound-demo/blob/master/main.js

【讨论】:

    【解决方案2】:

    来自react-native-sound文档:

    iOS:打开 Xcode 并将您的声音文件添加到项目中(右键单击 项目并选择将文件添加到 [PROJECTNAME])。

    那你就可以调用它了

    new Sound('Page_Turn.mp3',

    【讨论】:

      猜你喜欢
      • 2019-05-13
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多