Play audio local file with html - html

I'm trying to do something like this.
But I don't know why I'm not getting this thing work.
Here it is the codepen example:
$('input').on('change', function(e) {
var file = e.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$('audio source').attr('src', e.target.result);
}
reader.readAsDataURL(file);
});
The source tag is receiving the base64 mp3 file, but it doesn't load the file into browser.

You set the src attr directly on the audio element. fiddle
var $audio = $('#myAudio');
$('input').on('change', function(e) {
var target = e.currentTarget;
var file = target.files[0];
var reader = new FileReader();
console.log($audio[0]);
if (target.files && file) {
var reader = new FileReader();
reader.onload = function (e) {
$audio.attr('src', e.target.result);
$audio.play();
}
reader.readAsDataURL(file);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file">
<audio controls id="myAudio" autoplay></audio>

<audio controls>
<source src="yoraudio.ogg" type="audio/ogg">
<source src="youraudio.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
For more help visit
This is the simplest way to play audio

In UWP you can play a file directly that you can get by name from the Music Library as shown below. Just get permission to access the Music Library by checking the library in the "Capabilities" tag of your project properties.
picksinglefile();
var l = Windows.Storage.KnownFolders.musicLibrary;
var f = localStorage.getItem("alarmname").toString();
l.getFileAsync(f).then(function (file) {
// storagefile file is available
var s = window.URL.createObjectURL(file); // its a storage file, so create URL
player1.setAttribute("src", s);
player1.play(); // if autoplay is false or off
});
function picksinglefile() {
// Create the picker object and set options
var fop = new Windows.Storage.Pickers.FileOpenPicker();
fop.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.musicLibrary;
fop.fileTypeFilter.replaceAll([".mp3", ".wav"]);
fop.pickSingleFileAsync().then(function (file) {
if (file) {
localStorage.setItem("alarmname", file.name.toString());
} else {
alert("Operation Cancelled");
}
});

Related

React HTML5 Video controls

so I am trying to create a webcam type functionality where users can click record right in the browser and then record a video and then either download or upload it.
It is modelled on the site at https://www.tellamericaitsgreat.com/
So far I have code that will use the webcam and show the video as HTML5 video on the screen but it doesn't record (it just plays and pauses on the screen) or download/upload.
This has to be done in React. I am trying to use https://github.com/muaz-khan/RecordRTC
My code right now for the video is:
import React, { Component } from 'react';
import './Record.css';
class Record extends Component {
render() {
var RecordRTC = require('recordrtc');
function successCallback(stream){
var vid = document.querySelector('video');
vid.src = URL.createObjectURL(stream);
vid.muted = true;
var recorder = RecordRTC(stream, {
type: 'video'
});
recorder.startRecording();
setTimeout(function(){
recorder.stopRecording(function(){
var blob = recorder.blob;
var url = URL.createObjectURL(blob);
vid.src = url;
vid.muted = false;
});
}, 5 * 1000);
}
function errorCallback(error){
alert(error);
}
var mediaConstraints = {video: true, audio: true};
navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
return (
<video controls autoplay id="video"></video>
);
}
}
export default Record;

Download link for video file

I have a video for which I want to provide a download link. However, having created a simple Download tag, when I click on it (in Firefox & Chrome) it starts playing the video instead of allowing the video to be downloaded. Is there a way that works in all current browsers to force them to offer the save-as dialog?
Try using the download attribute.
<a href="myvideo.mp4" download>Download</a>
More at:
http://www.w3schools.com/tags/att_a_download.asp
you should also try this.
if (isVideo) {
var div = document.createElement('div');
div.className = "column";
var vid = document.createElement('video');
var source = document.createElement('source');
source.type = "video/mp4";
source.src = display_src;
vid.appendChild(source);
vid.poster;
vid.controls = true;
var alink = document.createElement('a');
alink.href = display_src;
alink.id = 'downlo_click';
}
alink.text = "Repost"
// window.open(alink, '_self');
div.appendChild(vid);
div.appendChild(alink);
document.getElementById('gamediv').appendChild(div)
document.getElementById('downlo_click').addEventListener('click', function() {
var x = new XMLHttpRequest();
x.open("GET", display_src, true);
x.responseType = 'blob';
x.onload = function(e) {
download(x.response, "abcd.mp4", "video/mp4");
}
x.send();
// window.open(alink, '_self');
// download("data:text/html,"display_src, display_src);
});
}

Embed camera frame in web app html5

I want to beuild web app that the user will upload a image from device camera.
I know that I can use <input type="file" accept="image/*" capture="camera">.
My question is that if there is a way to "embed" the camera screen in the page itself. In other words, I want that the screen will look like this:
I suggest you can read the article Capturing Audio & Video in HTML5.
Here is the code to access your camera:
<video autoplay></video>
<script>
var errorCallback = function(e) {
console.log('Reeeejected!', e);
};
// Not showing vendor prefixes.
navigator.getUserMedia({video: true, audio: true}, function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
// Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
// See crbug.com/110938.
video.onloadedmetadata = function(e) {
// Ready to go. Do some stuff.
};
}, errorCallback);
</script>
Taking screenshots:
<video autoplay></video>
<img src="">
<canvas style="display:none;"></canvas>
<script>
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var localMediaStream = null;
function snapshot() {
if (localMediaStream) {
ctx.drawImage(video, 0, 0);
// "image/webp" works in Chrome.
// Other browsers will fall back to image/png.
document.querySelector('img').src = canvas.toDataURL('image/webp');
}
}
video.addEventListener('click', snapshot, false);
// Not showing vendor prefixes or code that works cross-browser.
navigator.getUserMedia({video: true}, function(stream) {
video.src = window.URL.createObjectURL(stream);
localMediaStream = stream;
}, errorCallback);
</script>
Video tag is there HTML5 to handle this. and you need to use getUserMedia api to handle the streaming. most of the modern browsers supports it. To validate whether it is supported, use javascript to check that. You can try this:
if(navigator.getUserMedia()) ....
Here's a good tutorial on how to use a web cam to capture images. The same person also has a tutorial on capturing video to GIFs.
http://davidwalsh.name/browser-camera
HTML 5 Image capture tutorial & demo

How to get media stream object form HTML5 video element in javascript

all
I'm in peer to peer communication using webRTC , we have media stream object from the getUserMedia which is given as input stream to peerconnection. Here I need video stream from the selected video file from the local drive which is playing using Video element of HTML5.
Is it possible to create mediastream object from the video tag?
thanks,
suri
For now you can't add a media stream from a video tag, but it should be possible in the future, as it is explained on MDN
MediaStream objects have a single input and a single output. A MediaStream object generated by getUserMedia() is called local, and has as its source input one of the user's cameras or microphones. A non-local MediaStream may be representing to a media element, like or , a stream originating over the network, and obtained via the WebRTC PeerConnection API, or a stream created using the Web Audio API MediaStreamAudioSourceNode.
But you can use Media Source Extensions API to do what yo want : you have to put the local file into a stream and append in in a MediaSource object. You can learn more about MSE here : http://www.w3.org/TR/media-source/
And you can find a demo and source of the method above here
2021 update: It is now possible using MediaRecorder interface: https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder
Example from same page:
if (navigator.mediaDevices) {
console.log('getUserMedia supported.');
var constraints = { audio: true };
var chunks = [];
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
var mediaRecorder = new MediaRecorder(stream);
visualize(stream);
record.onclick = function() {
mediaRecorder.start();
console.log(mediaRecorder.state);
console.log("recorder started");
record.style.background = "red";
record.style.color = "black";
}
stop.onclick = function() {
mediaRecorder.stop();
console.log(mediaRecorder.state);
console.log("recorder stopped");
record.style.background = "";
record.style.color = "";
}
mediaRecorder.onstop = function(e) {
console.log("data available after MediaRecorder.stop() called.");
var clipName = prompt('Enter a name for your sound clip');
var clipContainer = document.createElement('article');
var clipLabel = document.createElement('p');
var audio = document.createElement('audio');
var deleteButton = document.createElement('button');
clipContainer.classList.add('clip');
audio.setAttribute('controls', '');
deleteButton.innerHTML = "Delete";
clipLabel.innerHTML = clipName;
clipContainer.appendChild(audio);
clipContainer.appendChild(clipLabel);
clipContainer.appendChild(deleteButton);
soundClips.appendChild(clipContainer);
audio.controls = true;
var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
chunks = [];
var audioURL = URL.createObjectURL(blob);
audio.src = audioURL;
console.log("recorder stopped");
deleteButton.onclick = function(e) {
evtTgt = e.target;
evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
}
}
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
}
})
.catch(function(err) {
console.log('The following error occurred: ' + err);
})
}
MDN also has a detailed mini tutorial: https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API/Recording_a_media_element

Use other source of sound effect when using firefox beside mp3

I'm trying to make a menu with sound after user clicks it. It works well in Chrome, safari, and even IE, but not Mozilla Firefox. I use mp3 file for the sound which can't run on firefox. Here's the code
function loadSound (src) {
var sound = document.createElement("audio");
if ("src" in sound) {
sound.autoPlay = false;
}
else {
sound = document.createElement("bgsound");
sound.volume = -10000;
sound.play = function () {
this.src = src;
this.volume = 0;
}
}
sound.src = src;
document.body.appendChild(sound);
return sound;
}
$(document).ready(function () {
var sound = loadSound("<?=base_url()?>sound/testing.mp3"); // preload
$(".main_nav a").click(function(){
var ids = $(this).attr("id").split("-");
var url = ids[2];
sound.play();
setTimeout (function(){window.location = url;}, 2000);
return false;
});
});
What type of audio file works in firefox? How do I change the source file when a user use firefox?
Ok, I understand your problem and I have a solution.
You could use this function that I make:
function getSupportedAudio(){
var testEl = document.createElement( "audio" ), mp3, ogg;
if ( testEl.canPlayType ) {
mp3 = "" !== testEl.canPlayType( 'audio/mpeg;' );
ogg = "" !== testEl.canPlayType( 'audio/ogg' );
}
if(mp3){
return ".mp3";
}
else{
return ".ogg";
}
}
In your function loadSound(src) use this:
sound.src = src+getSupportedAudio();
document.body.appendChild(sound);
And when you call the loadSound function, don't send the audio format in the parameter (but you need to have both files, ogg and mp3, in the same folder and with the same name):
var sound = loadSound("<?=base_url()?>sound/testing"); // preload