Few days back one of my friend sent me an audio message in Facebook messenger, the moment I was realized that I haven’t covered this audio recording system on 9lessons.info. Today I want to discuss how to publish a voice recording messages on newsfeed using Jquery and HTML5 with custom HTML5 audio player. Take a quick look at the live demo, make sure use the microphone for better result.
Download Script Live Demo
Database
Newsfeed table contains all the user update details.
CREATE TABLE newsfeed(
id INT PRIMARY KEY AUTO_INCREMENT,
userUpdate TEXT,
user_id_fk INT,
audioMessage TEXT,
status ENUM('0','1') DEFAULT '1');
id INT PRIMARY KEY AUTO_INCREMENT,
userUpdate TEXT,
user_id_fk INT,
audioMessage TEXT,
status ENUM('0','1') DEFAULT '1');
JavaScript
You have to include all these JavaScript library files.
<script src="recorderControl.js"></script>
<script src="js/jquery.min.2.1.js"></script> //Jquery
<script src="js/jquery.stopwatch.js"></script> //Jquery Stop Watch
<script src="recorder.js"></script>
<script type="text/javascript">
$(document).ready(function(){
-----
-----
-----
});
</script>
<script src="js/jquery.min.2.1.js"></script> //Jquery
<script src="js/jquery.stopwatch.js"></script> //Jquery Stop Watch
<script src="recorder.js"></script>
<script type="text/javascript">
$(document).ready(function(){
-----
-----
-----
});
</script>
Custom Audio Player HTML Code
HTML code for custom designed audio player, here the actual HTML5 player is in hidden mode. Number 10 refers to user's session id.
<div class="audioContainer">
<div class="audioProgress" id="audioProgress10'" style="width:0px"></div>
<div class="audioControl audioPlay" rel="play" id="10"></div>
<div class="audioTime" id="audioTime10'">00.00</div>
<div class="audioBar"></div>
<audio preload="auto" src="data:audio/mp3;base64,//sUxAAABAArMFRhgA.." type="audio/mpeg" class="a" id="audio10'"><source></audio>
</div>
<div class="audioProgress" id="audioProgress10'" style="width:0px"></div>
<div class="audioControl audioPlay" rel="play" id="10"></div>
<div class="audioTime" id="audioTime10'">00.00</div>
<div class="audioBar"></div>
<audio preload="auto" src="data:audio/mp3;base64,//sUxAAABAArMFRhgA.." type="audio/mpeg" class="a" id="audio10'"><source></audio>
</div>
Audio Player CSS
Focus on colored CSS properties.
audio{display:none}
.audioContainer
{
height:50px;width:250px;
border:solid 1px #dedede;
position:relative;
}
.audioProgress
{
height:50px;float:left;background-color:#f2f2f2;z-index:800
}
.audioControl
{
position: absolute;float:left;width:52px;height:48px;;
}
.audioTime
{
position: absolute;width: 45px;height: 20px;margin-left:199px;float:right;
}
.audioBar
{
height: 3px;
background-color: #cc0000;
position: absolute;width: 147px;margin-left: 53px;
}
.audioPlay
{
background:url('../images/play.png') no-repeat
}
.audioPause
{
background:url('../images/pause.png') no-repeat
}
.audioContainer
{
height:50px;width:250px;
border:solid 1px #dedede;
position:relative;
}
.audioProgress
{
height:50px;float:left;background-color:#f2f2f2;z-index:800
}
.audioControl
{
position: absolute;float:left;width:52px;height:48px;;
}
.audioTime
{
position: absolute;width: 45px;height: 20px;margin-left:199px;float:right;
}
.audioBar
{
height: 3px;
background-color: #cc0000;
position: absolute;width: 147px;margin-left: 53px;
}
.audioPlay
{
background:url('../images/play.png') no-repeat
}
.audioPause
{
background:url('../images/pause.png') no-repeat
}
Audio JavaScript
Contains JavaScript code $('body').on('click','.audioControl', function()- audioControl is the CLASS name of the DIV tag. Using $(this).attr("id") calling the player ID.
// Utility method that will give audio formatted time
getAudioTimeByDec = function(cTime,duration)
{
var duration = parseInt(duration),
currentTime = parseInt(cTime),
left = duration - currentTime, second, minute;
second = (left % 60);
minute = Math.floor(left / 60) % 60;
second = second < 10 ? "0"+second : second;
minute = minute < 10 ? "0"+minute : minute;
return minute+":"+second;
};
// Custom Audio Control using Jquery
$("body").on("click",".audioControl", function(e)
{
var ID=$(this).attr("id");
var progressArea = $("#audioProgress"+ID);
var audioTimer = $("#audioTime"+ID);
var audio = $("#audio"+ID);
var audioCtrl = $(this);
e.preventDefault();
var R=$(this).attr('rel');
if(R=='play')
{
$(this).removeClass('audioPlay').addClass('audioPause').attr("rel","pause");
audio.trigger('play');
}
else
{
$(this).removeClass('audioPause').addClass('audioPlay').attr("rel","play");
audio.trigger('pause');
}
// Audio Event listener, its listens audio time update events and updates Progress area and Timer area
audio.bind("timeupdate", function(e)
{
var audioDOM = audio.get(0);
audioTimer.text(getAudioTimeByDec(audioDOM.currentTime,audioDOM.duration));
var audioPos = (audioDOM.currentTime / audioDOM.duration) * 100;
progressArea.css('width',audioPos+"%");
if(audioPos=="100")
{
$("#"+ID).removeClass('audioPause').addClass('audioPlay').attr("rel","play");
audio.trigger('pause');
}
});
// Custom Audio Control End
});
getAudioTimeByDec = function(cTime,duration)
{
var duration = parseInt(duration),
currentTime = parseInt(cTime),
left = duration - currentTime, second, minute;
second = (left % 60);
minute = Math.floor(left / 60) % 60;
second = second < 10 ? "0"+second : second;
minute = minute < 10 ? "0"+minute : minute;
return minute+":"+second;
};
// Custom Audio Control using Jquery
$("body").on("click",".audioControl", function(e)
{
var ID=$(this).attr("id");
var progressArea = $("#audioProgress"+ID);
var audioTimer = $("#audioTime"+ID);
var audio = $("#audio"+ID);
var audioCtrl = $(this);
e.preventDefault();
var R=$(this).attr('rel');
if(R=='play')
{
$(this).removeClass('audioPlay').addClass('audioPause').attr("rel","pause");
audio.trigger('play');
}
else
{
$(this).removeClass('audioPause').addClass('audioPlay').attr("rel","play");
audio.trigger('pause');
}
// Audio Event listener, its listens audio time update events and updates Progress area and Timer area
audio.bind("timeupdate", function(e)
{
var audioDOM = audio.get(0);
audioTimer.text(getAudioTimeByDec(audioDOM.currentTime,audioDOM.duration));
var audioPos = (audioDOM.currentTime / audioDOM.duration) * 100;
progressArea.css('width',audioPos+"%");
if(audioPos=="100")
{
$("#"+ID).removeClass('audioPause').addClass('audioPlay').attr("rel","play");
audio.trigger('pause');
}
});
// Custom Audio Control End
});
Controlling audio controls with Jquery trigger()
Record Button HTML Code
Contains simple HTML code.
<img src="images/Microphone.png" id="recordButton" class="recordOff">
<span id="recordHelp">Allow your microphone.</span>
<div id="recordContainer" class="startContainer">
<div id="recordTime"> <span id="sw_m">00</span>:<span id="sw_s">00</span></div>
<div id="recordCircle" class="startRecord"><div id="recordText">Record</div></div>
</div>
<span id="recordHelp">Allow your microphone.</span>
<div id="recordContainer" class="startContainer">
<div id="recordTime"> <span id="sw_m">00</span>:<span id="sw_s">00</span></div>
<div id="recordCircle" class="startRecord"><div id="recordText">Record</div></div>
</div>
CSS
#recordCircle
{
margin: 0px auto;
font-weight: bold;
cursor: pointer;
width: 100px;
height: 100px;
text-align: center;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
}
{
margin: 0px auto;
font-weight: bold;
cursor: pointer;
width: 100px;
height: 100px;
text-align: center;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
}
Record Button JavaScript
This script calls record.js for recording the audio.
$("body").on('click','.recordOn',function()
{
$("#recordContainer").toggle();
});
//Record Button
$("#recordCircle").mousedown(function()
{
$(this).removeClass('startRecord').addClass('stopRecord');
$("#recordContainer").removeClass('startContainer').addClass('stopContainer');
$("#recordText").html("Stop");
$.stopwatch.startTimer('sw'); // Stopwatch Start
startRecording(this); // Audio Recording Start
}).mouseup(function()
{
$.stopwatch.resetTimer(); // Stopwatch Reset
$(this).removeClass('stopRecord').addClass('startRecord');
$("#recordContainer").removeClass('stopContainer').addClass('startContainer');
$("#recordText").html("Record");
stopRecording(this); // Audio Recording Stop
});
{
$("#recordContainer").toggle();
});
//Record Button
$("#recordCircle").mousedown(function()
{
$(this).removeClass('startRecord').addClass('stopRecord');
$("#recordContainer").removeClass('startContainer').addClass('stopContainer');
$("#recordText").html("Stop");
$.stopwatch.startTimer('sw'); // Stopwatch Start
startRecording(this); // Audio Recording Start
}).mouseup(function()
{
$.stopwatch.resetTimer(); // Stopwatch Reset
$(this).removeClass('stopRecord').addClass('startRecord');
$("#recordContainer").removeClass('stopContainer').addClass('startContainer');
$("#recordText").html("Record");
stopRecording(this); // Audio Recording Stop
});
record.js
Modified and included following code in record.js for storing the audio data in Base64 format.
function uploadAudioBase64(audiosrc)
{
var dataString ='audiosrc='+audiosrc;
$.ajax({
type: "POST",
url: "uploadAudio.php",
data: dataString,
cache: false,
success: function(html)
{
var ID = Number(new Date()); //Timestamp
var A='<div class="audioContainer">'
+'<div class="audioProgress" id="audioProgress'+ID+'" style="width:0px"></div>'
+'<div class="audioControl audioPlay" rel="play" id="'+ID+'"></div>'
+'<div class="audioTime" id="audioTime'+ID+'">00.00</div>'
+'<div class="audioBar"></div>'
+'<audio preload="auto" src="'+audiosrc+'" type="audio/mpeg" class="a" id="audio'+ID+'"><source></audio>'
+'</div>';
var B='<div class="stbody"><div class="stimg ">'
+'<a href="https://labs.9lessons.info/srinivas"><img src="http://www.gravatar.com/avatar/c9e85bd3f889cc998dd1bb71d832634b?d=mm&s=230" class="big_face " alt="You" ></a></div>'
+'<div class="sttext"><div class="sttext_content"><span class="sttext_span"><b><a href="https://labs.9lessons.info/srinivas">You</a></b> </span>'
+A
+'</div></div></div>';
$(".recordingslist").prepend(B);
}
});
}
{
var dataString ='audiosrc='+audiosrc;
$.ajax({
type: "POST",
url: "uploadAudio.php",
data: dataString,
cache: false,
success: function(html)
{
var ID = Number(new Date()); //Timestamp
var A='<div class="audioContainer">'
+'<div class="audioProgress" id="audioProgress'+ID+'" style="width:0px"></div>'
+'<div class="audioControl audioPlay" rel="play" id="'+ID+'"></div>'
+'<div class="audioTime" id="audioTime'+ID+'">00.00</div>'
+'<div class="audioBar"></div>'
+'<audio preload="auto" src="'+audiosrc+'" type="audio/mpeg" class="a" id="audio'+ID+'"><source></audio>'
+'</div>';
var B='<div class="stbody"><div class="stimg ">'
+'<a href="https://labs.9lessons.info/srinivas"><img src="http://www.gravatar.com/avatar/c9e85bd3f889cc998dd1bb71d832634b?d=mm&s=230" class="big_face " alt="You" ></a></div>'
+'<div class="sttext"><div class="sttext_content"><span class="sttext_span"><b><a href="https://labs.9lessons.info/srinivas">You</a></b> </span>'
+A
+'</div></div></div>';
$(".recordingslist").prepend(B);
}
});
}
updateAudio.php
Inserting the audio Base64 data into newsfeed along with user session id.
<?php
include('db.php');
$session_id='1';
if($_POST['audiosrc'] && !empty($session_id))
{
$audiosrc=$_POST['audiosrc'];
$query=mysqli_query($db,"INSERT INTO `newsfeed` (`user_id_fk`, `audioMessage`) VALUES ( '$session_id', '$audiosrc')")or die(mysqli_error($db));
}
?>
include('db.php');
$session_id='1';
if($_POST['audiosrc'] && !empty($session_id))
{
$audiosrc=$_POST['audiosrc'];
$query=mysqli_query($db,"INSERT INTO `newsfeed` (`user_id_fk`, `audioMessage`) VALUES ( '$session_id', '$audiosrc')")or die(mysqli_error($db));
}
?>
This way data will store audio data into newsfeed table.
db.php
Database connection you have to modify username, password and database values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD,DB_DATABASE) or die(mysqli_connect_error());
$path = "uploads/"; //Images upload folder
?>
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD,DB_DATABASE) or die(mysqli_connect_error());
$path = "uploads/"; //Images upload folder
?>
nice idea :)
ReplyDeleteI will try this great tutorial in my web thanks Srinivas
ReplyDeleteon pc it works good but on my smartphone when i click on "record" give me the copy & paste function.... how can i disable it???
ReplyDeleteGreat, but don't is working for me, on localhost and on server the time is always zero.
ReplyDeleteFantastic! The possibilities are endless. Good job!
ReplyDeleteAm your ardent follower from Nigeria.
IE failed to deliver as usual :D
Tested Results:
IE - Not Supported
Chrome - Supported
Firefox - Partially Supported
Safari - Not Supported
Opera - Not Supported
Use Modernizr for IE support
ReplyDeletehttp://www.9lessons.info/2012/12/responsive-web-design-css3.html
This comment has been removed by the author.
Deletegreat...
ReplyDeleteexcellent tutorial... : )
you are great. thank you for your tutor, i will use it.
ReplyDeleteSuch an awesome thing!! I would wish to try it.. Great tutorials!
ReplyDeleteI need help for installation. anyone to help me?
ReplyDeleteIts great that you also maintain mysqli extension in all your latest post.
ReplyDeletegreat
ReplyDeleteWhat about webcam video recording ?
ReplyDeleteNot supported smartphone
ReplyDeleteKnown issues
ReplyDeleteThe resulting mp3 recording will be longer by aproximetely 50%. So a 5 seconds recording will have a 10 seconds duration, with the last 5 seconds being empty. This may be caused by a buffer problem.
We get a loud mic record when we enable mic support.
Download não funciona....só subscribe ao feed burner.
ReplyDeleteGood and Easy understandable Tutorial Srinivas bro
ReplyDeletebut the recorded file have GAP! of the same amount of the recorded time
ReplyDeletei mean i have recorded my voice for 10 sec and the sound released was 10 sec + 10 sec of nothing ( 20 sec sound )
plus the VOice was sooooooooooooooo lowwwwwwwwwwwwwwwwwwwwwww
am facing same issue, please help me if you have any solutions. That problem is also on demo page
Deletecan someone add this to my wall script v7 please?
ReplyDeleteNice
ReplyDeleteGreat Idea very Informative for me, Thanks for Nice tutorial.
ReplyDeleteI realy enjoyed your articles and sharing the information with my friends
ReplyDeleteNice !!
ReplyDeleteits good script.I want to hidden voice record on my own website. can it be possible?
ReplyDeleteThank you
ReplyDeletei've subscribe but still can't download, why?
ReplyDeletei've verified my email and still can't download please help me.
ReplyDeleteGreat idea, but on smartphones dont working.
ReplyDeleteVery nice idea :-)
ReplyDeleteit working but not work properly way.
ReplyDeletehow to solve the sound echo problem
ReplyDeletegetUserMedia() no longer works on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS.
ReplyDeleteAdd HTTPS in URL
https://demos.9lessons.info/audioRecord/index.php
no funciona el boton update no muestra el texto junto la grabacion...y no muestra las gabaciones de la base de datos se borran al refrescar la pagina....hay errores en el scrip o asi es?
ReplyDeleteI HAVE PROBLEMS WITH THE HTML5 SCRIPT VOICE..GARDLES VOICE MESSAGES BUT DOES NOT SHOW THEM IN THE WALL BY RETURNING TO THE PAGE, THE RECORDINGS FOLDER IS ALWAYS EMPTY, WHAT ERROR MIGHT BE? AND DOES NOT LEAVE THE MESSAGE FAILED UPDATE BUTTON
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteen recordings folder nothing of audiosmhow to retorve audio from dabatase
ReplyDeleteThe demo is not working on my pc chrome
ReplyDeleteThe demo is not working on my pc safari how to working on my pc safari ??????
ReplyDeleteAuthor please update the project, base64 audio is not playing when I am trying to play by html audio tag.
ReplyDeleteDemo seems to be working for me on Chrome.
ReplyDeleteDemo is working for me onChrome, but has owful noise
ReplyDeletecan you make another tutorial more simple just to record voice message,upload en insert mysql,witout jquery
ReplyDeletegreat!
ReplyDeletei want to display username
ReplyDeletehow to capture the username?
$ session_id = '1';
$ session_id = 'username';
This comment has been removed by a blog administrator.
ReplyDelete