zmxv / react-native-sound

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

打印参数一切正常,播放没有声音,android #754

Open lpx18435404371 opened 3 years ago

lpx18435404371 commented 3 years ago

:beetle: Description

:beetle: What have you tried?

:beetle: Please post your code:

// Please post your code

:bulb: Possible solution

Is your issue with...

Are you using...

Which versions are you using?

Does the problem occur on...

If your problem is happening on a device, which device?

lpx18435404371 commented 3 years ago

const music = new Sound('msg.mp3', Sound.MAIN_BUNDLE, (error)=>{ if(error){ Alert.alert("播放失败。。。"); } else { Alert.alert("播放成功。。。"); } })

peiyinan1226 commented 3 years ago

你提交的代码不太全,所以不太清楚到底是哪里出了问题。 你贴出的只是加载文件部分的代码,也许你需要调用play()来播放声音,或者检查设备是否在静音模式并设置Sound.setCategory('Playback')。 你可以参考https://github.com/zmxv/react-native-sound#basic-usage的基础用例。

lpx18435404371 commented 3 years ago

onPress={()=>{music.play((success) => Alert.alert(${success}))},play()方法我调用并打印都为true, 设备我确定没有静音。

lpx18435404371 commented 3 years ago

// 本地音乐 Sound.setCategory('Playback') let musciPath = require('../../assets/mp3/msg.mp3'); let music = null if (Platform.OS === 'android') { music = new Sound(musciPath, '', (error)=>{ if(error){ Alert.alert("android播放失败。。。"); } else { Alert.alert("android播放成功。。。"); } }) } else { music = new Sound('msg.mp3', Sound.MAIN_BUNDLE, (error)=>{ if(error){ Alert.alert("ios播放失败。。。"); } else { Alert.alert("ios播放成功。。。"); } }) } 安卓两种方法都试过了,我还尝试过调用music.setCurrentTime(0); 并没有作用,打印回调参数一切正常,所有我不确定到底是那里的问题。

peiyinan1226 commented 3 years ago

我觉得你的加载文件代码应该是没有问题的,不过我建议你在Android的时候也将音频文件放在android/app/src/main/res/raw下面,这样也可以同ios一样直接使用文件名,也不需要判断设备系统了。 我感觉require的时候貌似需要一些加载时间。

import React from 'react'
import { Button } from 'react-native'
import Sound from 'react-native-sound'

export default function App () {
  Sound.setCategory('Playback')
  const musciPath = require('../../assets/mp3/msg.mp3')
  let music = null
  if (Platform.OS === 'android') {
    music = new Sound(musciPath, '', (error) => {
      if (error) {
        console.log('android播放失败。。。')
      } else {
        console.log('android播放成功。。。')
      }
    })
  } else {
    music = new Sound('msg.mp3', Sound.MAIN_BUNDLE, (error) => {
      if (error) {
        console.log('ios播放失败。。。')
      } else {
        console.log('ios播放成功。。。')
      }
    })
  }
  return (
    <Button
      title='button'
      onPress={() => {
        music.play((success) => {
          if (success) {
            console.log('successfully finished playing');
          } else {
            console.log('playback failed due to audio decoding errors');
          }
        })
      }}
    />
  )
}