React Native 0.69版本播放提示音问题求助
解决React Native 0.69播放提示音问题
方案一:使用react-native-audio-player包
这个包适配RN 0.60+版本,兼容性稳定,操作步骤如下:
- 安装依赖:
RN 0.69支持自动link,无需手动执行link命令。npm install react-native-audio-player --save # 或使用yarn yarn add react-native-audio-player - 准备音频文件:将提示音文件(如
alert.mp3)放入android/app/src/main/res/raw目录(Android,文件名不能含大写和空格),以及ios/{你的项目名}/Resources目录(iOS)。 - 调用播放:
import AudioPlayer from 'react-native-audio-player'; import { Platform } from 'react-native'; // 特定事件触发时执行 const playAlertSound = () => { const soundFile = Platform.OS === 'android' ? 'alert' : 'alert.mp3'; AudioPlayer.play(soundFile); };
方案二:使用expo-av(Expo项目适用)
如果你的项目基于Expo,官方推荐的expo-av是更可靠的选择:
- 安装依赖:
expo install expo-av - 播放实现:
import { Audio } from 'expo-av'; const playAlertSound = async () => { const { sound } = await Audio.Sound.createAsync( require('./assets/alert.mp3') // 替换为你的音频文件路径 ); await sound.playAsync(); // 播放结束后释放资源 sound.setOnPlaybackStatusUpdate(status => { if (status.didJustFinish) { sound.unloadAsync(); } }); };
方案三:原生模块极简实现(第三方包失效时)
如果以上方案都无法正常运行,可以直接写轻量原生模块:
Android端
- 新建
SoundModule类:import android.media.MediaPlayer; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; public class SoundModule extends ReactContextBaseJavaModule { private MediaPlayer mediaPlayer; public SoundModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "SoundModule"; } @ReactMethod public void playAlert() { if (mediaPlayer != null) { mediaPlayer.release(); } mediaPlayer = MediaPlayer.create(getReactApplicationContext(), R.raw.alert); mediaPlayer.start(); } } - 在
MainApplication的getPackages方法中注册模块,同时创建对应的SoundModulePackage类完成注册流程。 - JS端调用:
import { NativeModules } from 'react-native'; const { SoundModule } = NativeModules; // 事件触发时调用 SoundModule.playAlert();
iOS端
- 新建
SoundModule类:#import <React/RCTBridgeModule.h> #import <AVFoundation/AVFoundation.h> @interface SoundModule : NSObject <RCTBridgeModule> @end @implementation SoundModule RCT_EXPORT_MODULE(); RCT_EXPORT_METHOD(playAlert) { NSString *path = [[NSBundle mainBundle] pathForResource:@"alert" ofType:@"mp3"]; NSURL *url = [NSURL fileURLWithPath:path]; AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [player play]; } @end - JS端同样通过
NativeModules.SoundModule.playAlert()调用。
内容的提问来源于stack exchange,提问作者ValentinOsvaldo
相关产品推荐
相关产品推荐

