Cross-browser HTML5 audio player - javascript

I am using audio tag to play a wav audio, My url is genereted by URL.createObjectURL() and the url is like blob:http://localhost/9fa2ef06-ade6-4027-89f8-06cd2c176405
As the url has no extension, I have some issue with safari
The following code is works on chrome and not works on safari(Audio player is disabled)
<audio src="MY_BLOB_URL" type="audio/wav">
</audio>
The following code is works on safari and not works on chrome
<audio controls>
<source src="MY_BLOB_URL" type="audio/wav">
</audio>
I tried weird codes like the following and cannot find any way to works on both browsers
<audio src="MY_BLOB_URL" type="audio/wav">
<source src="MY_BLOB_URL" type="audio/wav">
</audio>
What's wrong here? And how can I have a cross-browser HTML5 audio player with single code?

I've tested the following code on Windows PC using Chrome, Edge & Firefox.
Let's hope it also works on Safari.
PS: For future readers, this code would also work with an MP3 blob (set as accept=".mp3").
<!DOCTYPE html>
<html><head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> </head>
<body>
<div style="z-index: 1; overflow:hidden; position: absolute; top: 100px; left: 50px">
<audio id="tag_Audio1" controls>
<source type="audio/wav">
</audio>
</div>
<br><br><br><br>
<div style="z-index: 1; overflow:hidden; position: absolute; top: 10px; left: 50px">
<p> Choose an WAV file...</p>
<input type="file" id="choose_media" accept=".wav" />
</div>
<script>
var file; var reader;
var tmpElement; //# is reference to aTag for holding image content.
var file_Blob; //# is reference to file BLOB (data of selected file).
const myAudio = document.getElementById("tag_Audio1");
document.getElementById("choose_media").addEventListener("change", onFile_Selected, false);
function onFile_Selected(evt)
{
file = evt.target.files[0]; //# access to selected file
reader = new FileReader();
reader.readAsDataURL(file); //# load selected file as Blob
reader.addEventListener("loadend", onFile_Loaded, false);
}
function onFile_Loaded(evt)
{
if (evt.target.readyState == FileReader.DONE)
{
//# remove any current SRC
myAudio.removeAttribute("src");
//# create blob
file_Blob = (window.URL || window.webkitURL).createObjectURL(file);
//# apply blob & test play
myAudio.setAttribute("src", file_Blob);
myAudio.load();
myAudio.play();
}
}
</script>
</body>
</html>

Related

Change div element content after the video finish

I was wondering if this is possible :
I have a movie with a Play button.
After click, the movie begins to play.
When the movie finish, I have a picture which cover my movie div.
Which options to use in my function:
<video src="video.com" id="myVideo">
</video>
<div class="images">
<img scr="some_pic.jpg" />
</div>
<script type='text/javascript'>
document.getElementById('myVideo').addEventListener('ended',myHandler,false);
const img = document.querySelector("img")
const video = document.querySelector("video")
function myHandler(e) {
// now the video has to hide, and show the img:
video.style.display = "none:
img.style.display = "block"
}
</script>
There are various options, including replacing the <video> tag with an <image> tag.
The easiest one I can think of is to have the image on a layer under the video, then when the video finishes, you can change layers (put image as the front layer and now video in the back layer).
When image is under the video, it has same size and position so to end-user it's invisible. This is set through the <style=> part where z-index is the layer position (higher number puts it above others of a lower number). The top and left options are the positions of up/down and left/right settings.
You can try using: (in the code below, I change their positions (not aligned) so you can see what is happening)...
<!DOCTYPE html>
<html>
<body>
<video id="myVideo" width="550" height="400" controls style=" z-index: 2; top: 50px; left: 100px; position: absolute; );">
<source src="some_video.mp4" type="video/mp4">
</video>
<div id="myPic" class="images" width="550" height="400" style=" z-index: 1; top: 80px; left: 140px; position: absolute; );">
<img src="some_pic.jpg" />
</div>
<script type='text/javascript'>
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
const img = document.getElementById('myPic');
const video = document.getElementById('myVideo');
function myHandler(e)
{
// now the video has to hide, and show the img:
//video.style.display = "none:
//img.style.display = "block"
//# swap their layer positioning
img.style.zIndex = "2"; //# makes top
video.style.zIndex = "1"; //# makes bottom
}
</script>
</body>
</html>
I'm not sure if there's something else to it other than simply showing an image when the video is not playing, if that's not the case, the video tag has a poster attribute:
<video controls poster="/images/w3html5.gif">
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

How to add mute/unmute button to browser audio player?

So I have my code here, and it works great. Only thing is there are no mute/unmute buttons and I have no idea how to add them.
<audio src="MUSIC URL" autoplay loop>
<p>Your browser does not support the audio element </p>
</audio>
I use this, get a play and pause button .png and use them. Then make a folder called audio and put the files in there for you music. I put the play and pause in a folder called images.
<style type="text/css">
audio {visibility: hidden; height: 0; width: 0; position: absolute; top: -300px; left: -300px;}
#pauseplay {float: right; width: 48px; height: 48px; overflow: hidden; cursor: pointer}
</style>
<audio controls loop>
<source src="**your website url here**/audio/waves.ogg" type="audio/ogg">
<source src="**your website url here**/audio/waves.mp3" type="audio/mpeg">
</audio>
<img id="pauseplay" src="**your website url here**/images/play.png" alt="button" title="Play/Pause">
<script type="text/javascript">
(function(){
var playing = !!('ontouchstart' in window) || !!('ontouchstart' in document.documentElement) || !!window.ontouchstart || (!!window.Touch && !!window.Touch.length) || !!window.onmsgesturechange || (window.DocumentTouch && window.document instanceof window.DocumentTouch),
snd = document.getElementsByTagName('audio')[0],
ctrl = document.getElementById('pauseplay');
playing = !playing;
ctrl.title = playing? 'Pause' : 'Play';
if(playing){snd.autoplay = false; ctrl.src = '**your website url** here/images/pause.png';}
ctrl.addEventListener('click', function(){
if(playing){
snd.pause();
} else {
snd.play();
}
playing = !playing;
ctrl.title = playing? 'Pause' : 'Play';
ctrl.src = playing? '**your website url here**/images/pause.png' : '**your website url here**/images/play.png';
}, false);
})();
</script>
If you want to see it live look at this site I made.
You should add controls attribute to audio tag.
If this attribute is present, the browser will offer controls to allow the user to control audio playback, including volume, seeking, and pause/resume playback.
developer.mozilla
<audio src="http://audiomicro-dev.s3.amazonaws.com/preview/1030/caca5b5fcde48f9" controls>
<p>Your browser does not support the audio element </p>
</audio>
Very easy:
<button onclick="document.getElementsByTagName('audio')[0].play();">Sound on</button>
<button onclick="document.getElementsByTagName('audio')[0].pause();">Sound off</button>
<audio autoplay preload="auto" loop src="your.mp3"></audio>
It is set on autoplay and loop, you can pause and resume by clicking the buttons. The best way to avoid diplaying the unsuitable browser player.

Play Local Video on PhoneGap/Cordova in Windows Apps

I'm developing Windows/Windows Phone 8.1 apps using PhoneGap(HTML, JS, CSS, JQM) and some Native/Windows Runtime Component. I want to play a video in a html page. My video file is located inside my Application Folder.
I don't know what's wrong. Please help me.
In the HTML,
I have added:
<div id="content">
<button onclick="domainObject.playVideo()" type="button" data-theme="b">Play Video</button>
<video id="video" src='' type='video/mp4' width="400" autoplay="autoplay" controls></video>
</div>
And in the JS:
var domainObject = {
playVideo: function () {
var vidPath = Windows.Storage.ApplicationData.current.localFolder.path + "\\test.mp4";
var video = document.getElementById('video');
var source = document.createElement('source');
source.setAttribute('src', vidPath);
video.appendChild(source);
video.load();
video.play();
}

too many audio tags make my website load very slowly. is there a solution?

I made a website (not on air yet) and I tested it live with some free hosting.
The website contains a map tag and a big picture within it.
I made it so if someone clicks on a part of the picture a specific audio will be heard, according to where he clicked.
My problem is that there are a lot of audio tags (about 300) and because there are lots of bandwidth-hogging files, it takes about 10 minutes until the website is fully loaded which means most of the audios don't work for several minutes.
I want to know if there is a way, maybe a responsive way with javascript or PHP that will allow me to make those audio tags only if the user clicks on the map. That way it will not use that much bandwidth. Also if anyone can think of a better way it will greatly appreciated.
I'm adding the javascript for the click event so you can see what it is all about -
$('#Swensens_maze').click(function(){
$('audio').each(function(){
this.pause(); // Stop playing
// Reset time
});
$('#Swensens_maze_audio').get(0).play();
return false;
});
This is one example from many. The "#swensens_maze" is the area tag and the "#Swensens_maze_audio" is the audio tag for it.
Your problem happens because browser tries to preload the audio for each audio tag.
So the answer is to set the attribute preload in the audio tag to value none
<audio preload="none">
EDIT The audio now automatically strats
EDIT 2 I have just remembered that an empty src is a bad practice, I will find a solution, the best one is to store the information in some other tag and then create a the audio tag with js
EDIT 3
JS FIDDLE VERSION 2
Better version,doesn't leave an empty src attribute, all the audio information are stored inside the the hidden input, once you click the area the audio tag is provided through JS inside the clicked div.
<html>
<head>
<script src="jq.js"></script>
<style>
.map {width:100%;height:75px;background:#bbb}
.c1 {background:#f2f2f2}
.c2 {background:#000}
.c3 {background:#cc4444}
</style>
</head>
<body>
<div class='map c1'>
<input type='hidden' data-original='1.mp3' data-format="audio/mpeg" />
</div>
<div class='map c2'>
<input type='hidden' data-original='2.mp3' data-format="audio/mpeg" />
</div>
<div class='map c3'>
<input type='hidden' data-original='3.mp3' data-format="audio/mpeg" />
</div>
<script>
$('div.map').click(function () {
$('audio').each(function () {
this.pause();
});
//Check if audio is already present, if true, then exit
if($(this).find('audio').length > 0)
return;
var childInput = $(this).find('input:hidden'), //Find information
audioTag = document.createElement("AUDIO"),// Create AUDIO element
audioSource = document.createElement("SOURCE"), //Create SOURCE element
audioType = childInput.attr('data-format'),//retrieve audio type, then you could checkif the browser supports this format
audioSrc = childInput.attr('data-original'); //retrieve audio src
//Set type and src of the source
audioSource.type= audioType;
audioSource.src= audioSrc;
//Enable controls and append SOURCE to AUDIO
audioTag.controls = true;
audioTag.appendChild(audioSource);
this.appendChild(audioTag);// Append the created audio tag to the clicked div
audioTag.load();//Load the src
audioTag.play();//Play the audio
return false;
});
</script>
</body>
</html>
OLDER ANSWER
Bad for empty src
$('div.map').click(function () {
$('audio').each(function () {
this.pause();
});
var audioTag = $(this).find('audio'),
sourceTag=audioTag.children('source');
if (sourceTag.attr('src')=='') {
sourceTag.attr('src', sourceTag.attr('data-original'));
audioTag.load()
}
audioTag.get(0).play();
return false;
});
Full page FIDDLE DEMO(the player doesn't appear, because there isn't any audio file):
<html>
<head>
<script src="jq.js"></script>
<style>
.map {
width:100%;
height:75px;
background:#bbb
}
.c1 {
background:#f2f2f2
}
.c2 {
background:#000
}
.c3 {
background:#cc4444
}
</style>
</head>
<body>
<div class='map c1'>
<audio controls>
<source data-original='1.mp3' src='' type="audio/mpeg" />
</audio>
</div>
<div class='map c2'>
<audio controls>
<source data-original='2.mp3' src='' type="audio/mpeg" />
</audio>
</div>
<div class='map c3'>
<audio controls>
<source data-original='3.mp3' src='' type="audio/mpeg" />
</audio>
</div>
<script>
$('div.map').click(function () {
$('audio').each(function () {
this.pause();
});
var audioTag = $(this).find('audio'),
sourceTag=audioTag.children('source');
if (sourceTag.attr('src')=='') {
sourceTag.attr('src', sourceTag.attr('data-original'));
audioTag.load()
}
audioTag.play();
return false;
});
</script>
</body>
</html>
<audio src="abc.mp3"controls class="audioDemo" preload="none"></audio>
<audio src="abc1.mp3"controls class="audioDemo" preload="none"></audio>
<audio src="abc2.mp3"controls class="audioDemo" preload="none"></audio>
<audio src="abc3.mp3"controls class="audioDemo" preload="none"></audio>
<audio src="abc4.mp3"controls class="audioDemo" preload="none"></audio>
Yes don't leave the src attribute empty, but give to src a valid blank and short file.mp3.
Then when user click or whatever replace the src by the good file, like this:
document.getElementById("audio8").src = "song.mp3";
Also, depending of how is made your page, if audio's appear block after block, have a look to lazysize.js for smoothly load your content when scroolling. Easy to use and powerful.
https://github.com/aFarkas/lazysizes
Your browser tries to preload the audio for each audio tag. So the answer is to set the attribute preload in the audio tag to value none
use can use: <audio controls preload="none">

making a audio file sound in javascript/html

I am trying to play a .ogg file which i also converted into a .mp3 file
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<body onclick = "playSound('file:///C:/Users/Rehaan/Downloads/myfirstrecording%20(3).ogg');">
<p id = "sound">
</p>
Click here to play the sound!
</body>
</html>
This is the java script file,
function playSound( url ){
document.getElementById("sound").innerHTML="<embed src='"+url+"' hidden=true autostart=true loop=false>";
}
I would recommend using the HTML5 audio tag.
<audio id="audio_samples" src="mymp3audiofile.mp3" controls></audio>
The audio tag supports mp3, ogg, and wav audio files.
Also, here are Javascript audio control functions that you may find useful:
<script type="text/javascript">
var audio = document.getElementById("audio_samples");
function playAudio() {
audio.play();
}
function pauseAudio() {
audio.pause();
}
function restartAudio() {
audio.load();
audio.play();
}
function louder() {
audio.volume += 0.1;
}
function softer() {
audio.volume -= 0.1;
}
</script>
<button onclick="playAudio()">Play</button>
<button onclick="pauseAudio()">Pause</button>
<button onclick="restartAudio()">Restart</button>
<button onclick="louder()">Louder</button>
<button onclick="softer()">Softer</button>
I hope this helps!
You can use HTML5 Tag which is <audio>. It can play .mp3, .ogg, .wav format.
This is an example that I got from w3schools.
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>

Categories

Resources