Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Expo Toggle Audio On and Off

I want to toggle a sound on and off across my react native expo app, however it's resulting sound overlapping when I click multiple times on and off & I am unsure if I need to set state on audio? I couldn't seem to find any good examples here - https://docs.expo.io/versions/latest/sdk/av/ unsure what I am doing wrong, newbie to RN.

As you can see this is a headerbutton which has to work across the whole app not just one screen.

Here is my snack - https://snack.expo.io/@roshambo/sound-toggle-on-and-off

import React, { useState } from "react";
import { HeaderButton } from "react-navigation-header-buttons";
import { Ionicons } from "@expo/vector-icons";
import { Audio } from "expo-av";

const CustomHeaderButton = props => {
const [soundIcon, setSoundIcon] = useState(false);

const soundObject = new Audio.Sound();
(async () => {
  await soundObject.loadAsync(require("../assets/bglaughs.mp3"), {
    volume: 0.25,
    isLooping: true,
    shouldPlay: true,
    isMuted: true
  });
})();

const toggleSound = () => {
  setSoundIcon(prevState => !prevState);
  soundObject.setOnPlaybackStatusUpdate(this._onPlaybackStatusUpdate);
};

_onPlaybackStatusUpdate = playbackStatus => {
  if (playbackStatus.isMuted) {
    playSound();
  } else {
    stopSound();
  }
};

const stopSound = async () => {
  try {
    await soundObject.stopAsync();
  } catch (error) {
    console.log("sound couldn't pause");
  }
};

const playSound = async () => {
  try {
    await soundObject.setIsMutedAsync(false);
    await soundObject.playAsync();
  } catch (error) {
    console.log("sound couldn't play");
  }  
};

return (
<HeaderButton
  {...props}
  IconComponent={Ionicons}
  iconSize={23}
  iconName={soundIcon ? "ios-volume-high" : "ios-volume-off"}
  onPress={toggleSound}
  />
  );
};

export default CustomHeaderButton;

UPDATE:

Here is my working code based off Oleg's answer as well as my implementation on redux.

Component

import React from "react";
import { HeaderButton } from "react-navigation-header-buttons";
import { useDispatch, useSelector } from "react-redux";

import * as soundActions from "../store/actions/sound-action";

import { Ionicons } from "@expo/vector-icons";

const CustomHeaderButton = props => {

  const sound = useSelector(state => state.sound.soundState);

  const dispatch = useDispatch();

  return (
    <HeaderButton
      {...props}
      IconComponent={Ionicons}
      iconSize={23}
      iconName={sound === "playing" ? "ios-volume-high" : "ios-volume-off"}
      onPress={() => {
        dispatch(soundActions.toggleSound(sound));
      }}
    />
  );
};

export default CustomHeaderButton;

Reducer

import { TOGGLE_SOUND } from "../actions/sound-action";

import { Audio } from "expo-av";

const initialState = {
  soundState: "nosound"
};

export default (state = initialState, action) => {
  switch (action.type) {
    case TOGGLE_SOUND:
      if (state.soundState === "nosound") {
        (async () => {
          const { sound } = await Audio.Sound.createAsync(
            require("../../assets/bglaughs.mp3"),
            {
              shouldPlay: true,
              volume: 0.25,
              isLooping: true
            }
          );
          this.sound = sound;
        })();
        return {
          ...state,
          soundState: "playing"
        };
      } else if (state.soundState === "playing") {
        (async () => {
          if (this.sound !== null) {
            await this.sound.pauseAsync();
          }
        })();
        return { ...state, soundState: "donepause" };
      } else if (state.soundState === "donepause") {
        (async () => {
          await this.sound.playAsync();
        })();
        return { soundState: "playing" };
      }
  }
  return state;
};
like image 471
roshambo Avatar asked Feb 01 '26 03:02

roshambo


1 Answers

I created snack answer for your question: You have to pay attention to new way create sound and flag loop set to false.

https://snack.expo.io/@djalik/sound-toggle-on-and-off

like image 104
Oleg Avatar answered Feb 03 '26 00:02

Oleg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!