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

send audio messages throught pusher channel #381

Closed
realrecordzLab opened this issue Sep 5, 2019 · 6 comments
Closed

send audio messages throught pusher channel #381

realrecordzLab opened this issue Sep 5, 2019 · 6 comments

Comments

@realrecordzLab
Copy link

I wanna implement an authentication without using laravel and a way to send audio messages using the pusher created channel. Can anyone help me?I never implemented audio sending and I'm not sure on how to proceed with the users authentication on the php side, and how to correctly send and retrive the audio data using pusher.

This is the code of the webRTC demo that pushers will offer on github (I've removed the webrtc because it will leave the sognaling open and this consume my pusher api quota), I did some modifications to integrate a button for audio recording. I've tried to send it throught the pusher connection, but if I send a blob url, it will give me an error when the message is received net::ERR_REQUEST_RANGE_NOT_SATISFIABLE, I have no idea of how to pass the data?

For the authentication, I want to use private channels, I want to understand what I need to put in my PHP file to authorize the users for a room.

JS code

Pusher.log = function(message) {
  if (window.console && window.console.log) {
    window.console.log(message);
  }
};
const pusher = new Pusher("12xxxxxxxxxxx", { cluster: "eu" });

pusher.connection.bind("state_change", function(states) {
  switch (states.current) {
    case "connected":
      socketId = pusher.connection.socket_id;
      console.log(socketId);
      break;
    case "disconnected":
    case "failed":
    case "unavailable":
      break;
  }
});

pusher.bind("message", function(message) {
  console.log(message);
    addMessage(message, socketId, false);
});

// Demo DOM elements
var channelInput = $('input[name="channelName"]');
var createChannelBtn = $(".demo-chat-create");
var joinChannelBtn = $(".demo-chat-join");
var messageInput = $(".demo-chat-message-input");
var sendBtn = $(".demo-chat-send");
var messageList = $(".demo-chat-messages");

// Set up DOM listeners
$(document).on("click", ".demo-chat-create" ,onCreateChannel);
$(document).on("click", ".demo-chat-join" ,onJoinChannel);
$(document).on("click", ".demo-chat-send" ,onSendMessage);
$(document).on("keydown", ".demo-chat-message-input" ,onMessageKeyDown);
// Storage of Pusher connection socket ID
var socketId;

var chunks = [];

$(document).on("click", ".audio-chat",function(){
  console.log('clicked');
  var channel = $('input[name="channelName"]').val();
  navigator.mediaDevices.getUserMedia({
    audio: true
  })
  .then(function(stream){
    var mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.start();
    console.log(mediaRecorder.state);
    console.log("recorder started");

    mediaRecorder.ondataavailable = function(e) {
      chunks.push(e.data);
      console.log(chunks);
    }
    setTimeout(function(){
      mediaRecorder.stop();
      console.log(mediaRecorder.state);
      console.log("recorder stopped");
      var blob = new Blob(chunks, {'type':'audio/webm; codecs=opus'});
      //console.log(blob);
      chunks = [];
      const audioUrl = URL.createObjectURL(blob);
      var data = {channel:channel,message:audioUrl,socketId:socketId}
      $.post('api/message.php', data);
    }, 5000);
  });
});

function onCreateChannel(e){
  e.preventDefault();
  var channelName = $('input[name="channelName"]').val();
  console.log(channelName);
  if (!channelName) {
    console.log("No channel name given");
    return;
  }
  // Subscribe to Pusher signalling channel
  pusher.subscribe(channelName);
  // Monitor Pusher connection state
  disableConnectInput();
};

function onJoinChannel(e){
  e.preventDefault();
  var channelName = $('input[name="channelName"]').val();
  console.log(channelName);
  if (!channelName) {
    console.log("No channel name given");
    return;
  }
  pusher.subscribe(channelName);
  disableConnectInput();
};

function onSendMessage(e) {
  e.preventDefault();
  var message = $('input[name="message"]').val();
  var channel = $('input[name="channelName"]').val();
  if (!message) {
    console.log("No message given");
    return;
  }
  var data = {channel:channel,message:message,socketId:socketId}
  $.post('api/message.php', data);
  addMessage(message, socketId, true);
  $('input[name="message"]').val(null);
};

function onMessageKeyDown(event) {
  if (event.keyCode == 13){
    onSendMessage();
  }
};

function addMessage(message, socketId, self){
  var messages = $(".demo-chat-messages").find("list-group-item");
  // Check for any messages that need to be removed
  var messageCount = messages.length;
  for (var i = 0; i < messageCount; i++) {
    var msg = messages[i];

    if (msg.dataset.remove === "true") {
      $(".demo-chat-messages").remove(msg);
    }
  };

  var newMessage = document.createElement("li");
  newMessage.classList.add("list-group-item");

  if (self) {
    newMessage.classList.add("self");
    newMessage.innerHTML = "<span class='badge'>You</span><p>" + message + "</p>";
  } else {
    newMessage.innerHTML = "<span class='badge'>" + socketId + "</span><p>" + message + "</p>";
  }

  $(".demo-chat-messages").append(newMessage);
};

function disableConnectInput() {
  channelInput.prop('disabled', true);
  createChannelBtn.prop('disabled' , true);
  joinChannelBtn.prop('disabled' , true);
};

PHP

<?php
require_once 'config.php';
require_once __DIR__.'/vendor/autoload.php';

class MyLogger {
  public function log( $msg ) {
    print_r( $msg . "\n" );
  }
}

// TODO: Check for valid POST data

$pusher = new Pusher\Pusher(APP_KEY, APP_SECRET, APP_ID, array('cluster' => APP_CLUSTER));

//uncomment to enable pusher logging!
$pusher->set_logger( new MyLogger() );

$pusher->trigger($_POST["channel"], "message", $_POST["message"], $_POST["socketId"], true);

header("Status: 200");
?>
@syrsly
Copy link

syrsly commented Sep 9, 2019

Please explain why you're trying to send the file through Pusher. You should ideally store the file on your own server and only send the file's url to the user(s).

@realrecordzLab
Copy link
Author

@joshmaines Because it's for a real time app, but I've solved by switching to socket.io and a dedicated server, pusher is not able to send binary data over the channels.

@syrsly
Copy link

syrsly commented Sep 10, 2019

You can send binary data as a string (convert it) as long as it fits inside the size limitations of a single message.

@daslicht
Copy link

You can send binary data as a string (convert it) as long as it fits inside the size limitations of a single message.
is there somewhere an example how to ?

@Hateem76
Copy link

@joshmaines Because it's for a real time app, but I've solved by switching to socket.io and a dedicated server, pusher is not able to send binary data over the channels.
bro I have a question,, how to use websockets in hosting server? Is it possible in shared hosting OR do I need any other hosting plan? Thanks.

@syrsly
Copy link

syrsly commented Feb 1, 2023

bro I have a question,, how to use websockets in hosting server? Is it possible in shared hosting OR do I need any other hosting plan? Thanks.

You can't normally use shared hosting for services like Pusher, but in the case of Pusher, you can accomplish using it on shared hosting, because it's an external service you connect to using an API. here's a link to the getting started docs: https://pusher.com/docs/channels/getting_started/javascript/

Edit: Most shared hosting won't give you the ability to install the Pusher and Node libraries using NPM, but you may be able to get around this. I'd recommend getting a VPS (virtual private server) account somewhere as that's easier to work with (less limitations anyway) and doesn't have to cost a lot.

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

4 participants