首页 > web前端 > js教程 > 正文

在 Expo 应用中添加声音和震动通知

心靈之曲
发布: 2025-08-22 17:12:18
原创
713人浏览过

在 expo 应用中添加声音和震动通知

在 Expo 应用中添加声音和震动通知

正如摘要所述,本文将指导你如何在 Expo 应用中集成声音和震动通知,以增强用户体验。我们将探讨如何使用 expo-av 和 react-native 提供的 Vibration API 实现这些功能,并重点关注权限处理和正确触发通知的时机。

集成声音通知

要实现声音通知,我们需要使用 expo-av 库。 首先,确保你已经安装了该库:

npx expo install expo-av
登录后复制

以下是一个基本示例,展示了如何在收到通知时播放声音:

import { useEffect } from "react";
import * as Notifications from "expo-notifications";
import { Alert } from "react-native";
import React from "react";
import { useNavigation } from "@react-navigation/native";
import { Audio } from 'expo-av';

Notifications.setNotificationHandler({
  handleNotification: async () => {
    return {
      shouldPlaySound: true,
      shouldSetBadge: false,
      shouldShowAlert: true,
    };
  },
});

const HandleNotifications = () => {
  const navigation = useNavigation();

  useEffect(() => {
    async function configurePushNotifications() {
      const { status } = await Notifications.getPermissionsAsync();
      let finalStatus = status;
      if (finalStatus !== "granted") {
        const { status } = await Notifications.requestPermissionsAsync();
        finalStatus = status;
      }
      if (finalStatus !== "granted") {
        Alert.alert(
          "Permiso requerido",
          "Se requieren notificaciones locales para recibir alertas cuando vencen los recordatorios."
        );
        return;
      }
    }

    configurePushNotifications();
  }, []);

  useEffect(() => {
    const subscription = Notifications.addNotificationResponseReceivedListener(
      (response) => {
        console.log("RESPONSE", response);
        const reminderId = response.notification.request.content.data.reminderId;
        if (reminderId) {
          navigation.navigate("ModifyReminder", { reminderId });
        }
      }
    );

    return () => subscription.remove();
  }, []);

  useEffect(() => {
    let soundObject = null;

    async function playSound() {
      soundObject = new Audio.Sound();
      try {
        await soundObject.loadAsync(require('../assets/sonido.mp3'));
        await soundObject.playAsync();
      } catch (error) {
        console.log(error);
      }
    }

    playSound();

    return () => {
      if (soundObject) {
        soundObject.stopAsync();
        soundObject.unloadAsync();
      }
    };
  }, []);

  useEffect(() => {
    const appFocusSubscription = Notifications.addNotificationResponseReceivedListener(() => {
      Audio.setIsEnabledAsync(false);
    });

    const appBlurSubscription = Notifications.addNotificationResponseReceivedListener(() => {
      Audio.setIsEnabledAsync(true);
    });

    return () => {
      appFocusSubscription.remove();
      appBlurSubscription.remove();
    };
  }, []);

  return <React.Fragment />;
};

export default HandleNotifications;
登录后复制

代码解释:

  1. 导入必要的模块: 导入 Audio 来自 expo-av 和 Notifications 来自 expo-notifications.
  2. 设置通知处理程序: 使用 Notifications.setNotificationHandler 配置通知的处理方式,确保 shouldPlaySound 设置为 true。
  3. 加载声音文件: 使用 Audio.Sound.createAsync 加载你的声音文件 (例如 sonido.mp3)。
  4. 播放声音: 创建一个 playSound 函数,使用 soundObject.playAsync() 播放声音。确保在组件卸载时停止并卸载声音对象,以避免内存泄漏。
  5. 解决声音循环播放问题: 使用 Audio.setIsEnabledAsync 在应用获得焦点和失去焦点时控制声音的播放,避免声音在应用打开时持续播放。

注意事项:

  • 确保你的声音文件路径正确。
  • 检查设备是否允许应用播放声音。
  • 处理异步操作的错误,例如声音文件加载失败。

集成震动通知

要实现震动通知,可以使用 react-native 提供的 Vibration API。 首先,确保你已经导入了该库:

import { Vibration } from 'react-native';
登录后复制

以下是一个基本示例,展示了如何在收到通知时触发震动:

import { Vibration } from 'react-native';

// 在收到通知时触发震动
const handleNotification = () => {
  Vibration.vibrate(); // 默认震动模式
};
登录后复制

你也可以自定义震动模式:

人声去除
人声去除

用强大的AI算法将声音从音乐中分离出来

人声去除 23
查看详情 人声去除
import { Vibration } from 'react-native';

// 自定义震动模式
const handleNotification = () => {
  const pattern = [0, 500, 200, 500]; // 停止 0ms, 震动 500ms, 停止 200ms, 震动 500ms
  Vibration.vibrate(pattern);
};
登录后复制

代码解释:

  1. 导入 Vibration: 导入 Vibration 来自 react-native.
  2. 触发震动: 使用 Vibration.vibrate() 触发震动。你可以使用默认震动模式,也可以自定义震动模式。

注意事项:

  • 某些设备可能不支持震动功能。
  • 过度使用震动可能会影响用户体验。

权限处理

在 Android 设备上,你需要确保应用具有播放声音和震动的权限。 通常情况下,Expo 会自动处理这些权限,但如果遇到问题,可以手动请求权限:

import * as Permissions from 'expo-permissions';

async function requestPermissions() {
  const { status } = await Permissions.askAsync(Permissions.AUDIO_RECORDING, Permissions.NOTIFICATIONS);
  if (status !== 'granted') {
    Alert.alert('权限不足', '请在设置中授予应用声音和通知权限。');
  }
}

useEffect(() => {
  requestPermissions();
}, []);
登录后复制

代码解释:

  1. 导入 Permissions: 导入 Permissions 来自 expo-permissions.
  2. 请求权限: 使用 Permissions.askAsync 请求声音和通知权限。
  3. 处理权限状态: 检查权限状态,如果未授予权限,则显示警告信息。

总结

通过本文,你学习了如何在 Expo 应用中添加声音和震动通知。 关键步骤包括:

  • 使用 expo-av 库实现声音通知。
  • 使用 react-native 提供的 Vibration API 实现震动通知。
  • 处理权限,确保应用具有播放声音和震动的权限。
  • 在正确的时间触发通知,例如在收到推送通知时。

希望本文对你有所帮助! 记住,良好的用户体验来自于细致的打磨和不断的优化。

以上就是在 Expo 应用中添加声音和震动通知的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号