I want to get real-time notifications with sound when an order is placed into my app. I'm using laravel 8 and pusher to that. I get real-time alerts but the sound does not work perfectly. When an order is placed first time sound does not play, after that sound is played perfectly. Here is my code structure ...
My event class
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MyEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastOn()
{
return ['my-channel'];
}
public function broadcastAs()
{
return 'my-event';
}
}
Here is the js code
Pusher.logToConsole = true;
var pusher = new Pusher('***pusher key***', {
cluster: 'ap2'
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
alert(data.message)
playAudio();
});
function playAudio() {
var x = new Audio('http://127.0.0.1:8000/backend/assets/notification.mp3');
// Show loading animation.
var playPromise = x.play();
if (playPromise !== undefined) {
playPromise.then(_ => {
x.play();.
})
.catch(error => {
});
}
}
Here is my controller
public function store(){
event(new MyEvent('1 new order has been placed'));
return 'Success';
}
When I hit this route for the first time, real-time alert message is shown but the sound does not play. It shows this error
DOMException: play() failed because the user didn't interact with the document first.
https://some link
And it works perfectly after first time
I would like to give a sound notification to the admin if the order is placed, now how can I do that?