xiqi / react-native-live-audio-stream

Get live audio stream data for React Native (works for iOS and Android)
MIT License
80 stars 33 forks source link

Live Audio Streaming not working in socket using when i receiving the audio file facing the error like Failed to load sound {"extra": -2147483648, "what": 1} #29

Open DevaPandiyan opened 4 months ago

DevaPandiyan commented 4 months ago

`import { Alert, Button, PermissionsAndroid, Platform, StyleSheet, Text, View } from 'react-native'; import React, { useEffect, useState } from 'react'; import io from 'socket.io-client'; import { useNavigation } from '@react-navigation/native'; import Sound from 'react-native-sound'; import LiveAudioStream from 'react-native-live-audio-stream'; import { Buffer } from 'buffer'; import RNFS from 'react-native-fs';

Sound.setCategory('Playback');

const LiveStreaming = () => { const navigation = useNavigation(); const [socket, setSocket] = useState(null); const [isStreaming, setIsStreaming] = useState(false); const [initial, setInitial] = useState(false);

useEffect(() => { const socketInstance = io('https://devtamilcalendar.shrewdbs.com', { path: '/audio-meeting' });

socketInstance.on('connect', () => {
  console.log('Connected to server:', socketInstance.id);
});

socketInstance.on('audio_receive',  (chunk) => {
  console.log('audio received', chunk);
 receiveAudio(chunk) // Play received audio in real-time
});

socketInstance.on('user_joined', (isSpeaker, list) => {
  console.log("user Joined", list);
});

socketInstance.on('participantsUpdated', list => {
  console.log("participant Joined", list);
});

socketInstance.on('join', () => {
  console.log('joiner');
});

socketInstance.on('disconnect', () => {
  console.log('Disconnected from server');
});

socketInstance.on("allCleared", () => {
  console.log("allCleared room")
});

setSocket(socketInstance);

return () => {
    socketInstance.disconnect();
    socketInstance.off('connect', () => {
      console.log('Connected to server:---', socketInstance.id);
    });
    socketInstance.off('disconnect', async () => {

      // Remove existing tracks

      console.log('Disconnected from server---');
    });
    socketInstance.off();
};

}, []);

const ListenerJoin = () => { if (socket) { const data = { username: "Raone", isSpeaker: false, }; socket.emit('join', data); } };

const SpeakerJoin = () => { if (socket) { const data = { username: "Ravana", isSpeaker: true, }; socket.emit('join', data); } };

const requestAudioPermission = async () => { if (Platform.OS === 'android') { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, { title: 'Audio Permission', message: 'App needs access to your microphone to record audio.', buttonNeutral: 'Ask Me Later', buttonNegative: 'Cancel', buttonPositive: 'OK', }, ); if (granted !== PermissionsAndroid.RESULTS.GRANTED) { console.log('Audio permission denied'); } } catch (err) { console.warn(err); } } };

useEffect(() => {

  if (Platform.OS === 'android') {
    requestAudioPermission();
  }

  const options = {
    sampleRate: 32000,  // default is 44100 but 32000 is adequate for accurate voice recognition
    channels: 1,        // 1 or 2, default 1
    bitsPerSample: 16,  // 8 or 16, default 16
    audioSource: 6,     // android only (voice recognition)
    bufferSize: 4096    // default is 2048
  };

  LiveAudioStream.init(options);

console.log("isStreaming",isStreaming)

return () => {
  LiveAudioStream.stop();
};

}, [ ]);

const startStreaming = () => { if (socket && !isStreaming) { LiveAudioStream.start(); LiveAudioStream.on('data', data => { var chunk = Buffer.from(data, 'base64'); socket.emit('audio_emit', data); // console.log('Emitted audio chunk:',data); });

  setIsStreaming(true);

} else {
  Alert.alert('Error', 'Socket connection is not established or already streaming.');
}

};

const receiveAudio = async (chunk) => { console.log("Received audio chunk:", chunk); await playSound(chunk); };

const stopStreaming = () => { if (isStreaming) { LiveAudioStream.stop(); setIsStreaming(false); } };

const AdminClear = () => { if (socket) { socket.emit('adminCommand', "clearAll"); } };

const playSound = async (chunk) => { try {

const timestamp = Date.now();

// const buffer = Buffer.from(chunk, 'base64');
const base64String = 'data:audio/wav;base64,' + chunk;
const filePath = `${RNFS.DocumentDirectoryPath}/temp_sound_${timestamp}.wav`;

// Ensure the directory exists
await RNFS.mkdir(RNFS.DocumentDirectoryPath);

// Write the audio chunk to a file
await RNFS.writeFile(filePath,chunk, 'base64').then(async ()=>{
  const fileExists = await RNFS.exists(filePath);
  if (!fileExists) {
    console.log('Audio file does not exist');
    return;
  }
  // Play the audio file
  const sound = new Sound(filePath,'', (error) => {
    if (error) {
      console.log('Failed to load sound', error);
      return;
    }

    sound.play((success) => {
      if (success) {
        console.log('Successfully finished playing');
      } else {
        console.log('Playback failed due to audio decoding errors');
      }
      sound.release();
    });
  });

});

} catch (err) { console.log('Failed to play sound', err); } };

return (