Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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 this issue May 21, 2024 · 0 comments

Comments

@DevaPandiyan
Copy link

`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 (







);
};

export default LiveStreaming;

const styles = StyleSheet.create({

});
`

@DevaPandiyan DevaPandiyan changed the title Live Audio Streaming not working Live Audio Streaming not working in socket May 21, 2024
@DevaPandiyan DevaPandiyan changed the title Live Audio Streaming not working in socket 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} May 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant