Echo $row database value inside a javascript - javascript

How can i display database value $row in javascript?
At line 3 const source = 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8'; I want the link/url get from database. base on url id domain.com/video.php?id=12
I already try like this but doesn't work const source = '<?php echo $row["video_url"]; ?>'
Here is the code
<script>
document.addEventListener('DOMContentLoaded', () => {
const source = 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8';
const video = document.querySelector('video');
// For more options see: https://github.com/sampotts/plyr/#options
// captions.update is required for captions to work with hls.js
const player = new Plyr(video, {captions: {active: true, update: true, language: 'en'}});
if (!Hls.isSupported()) {
video.src = source;
} else {
// For more Hls.js options, see https://github.com/dailymotion/hls.js
const hls = new Hls();
hls.loadSource(source);
hls.attachMedia(video);
window.hls = hls;
// Handle changing captions
player.on('languagechange', () => {
// Caption support is still flaky. See: https://github.com/sampotts/plyr/issues/994
setTimeout(() => hls.subtitleTrack = player.currentTrack, 50);
});
}
// Expose player so it can be used from the console
window.player = player;
});
</script>
EDITED: The output for this script is empty const source = ''

Related

Choosing audio format when saving data locally on a web app

I have a web app getting some audio recording input from the user.
And there is a button to save it locally as an audio file.
The resulting file I am getting is of ogg-opus format. Concretely when I use the file command I get this in the terminal:
MyMac$ file Clip.wav
Clip.wav: Ogg data, Opus audio,
MyMac$
I can check that the recording is all right using VLC.
On the other hand I can't play the file with afplay as is normally possible with an mp3, m4a or wav file.
MyMac$ afplay Clip.wav
Error: AudioFileOpen failed ('typ?')
MyMac$
Here follows my relevant code:
if (navigator.mediaDevices.getUserMedia) {
// getUserMedia is supported.
const constraints = { audio: true };
let chunks = [];
let onSuccess = function(stream) {
const mediaRecorder = new MediaRecorder(stream);
visualize(stream);
........
mediaRecorder.onstop = function(e) {
........
audio.setAttribute('controls', '');
........
audio.controls = true;
const blob = new Blob(chunks, { 'type' : 'audio/wav;codecs=0' });
chunks = [];
........
upload.addEventListener("click",
function(event) {loadToServer(blob)})
........
}
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
}
}
let onError = function(err) {
console.log('The following error occured: ' + err);
}
navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
} else {
console.log('getUserMedia not supported on your browser!');
}
I would like to know how to change my code in order to generate a proper wav file or even mp3.
Note:
I have made trials modifying this line of code:
const blob = new Blob(chunks, { 'type' : 'audio/wav;codecs=0' });
in various ways, but is has no effect at all.
In order to specify the mimeType of your recording you need to tell the MediaRecorder which mimeType you prefer before it starts the recording.
- const mediaRecorder = new MediaRecorder(stream);
+ const mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/wav' });
Unfortunately audio/wav is not supported by any browser. You will get an error when trying the snippet above.
Since I needed wav recordings as well I built a library which is meant to add this functionality. It's called extendable-media-recorder because it could be extended with any other (audio) codec you like.
If you don't want to use a third party library and keep the browser using the codec it likes best you can save your file like this in order to get a valid file with the correct suffix.
- const blob = new Blob(chunks, { 'type' : 'audio/wav;codecs=0' });
+ const blob = new Blob(chunks, { 'type' : mediaRecorder.mimeType });
The suffix would then be the portion of the type after the slash and before a possible semicolon.
Here is an example of a full HTML document that uses jspm to load extendable-media-recorder without a bundler.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<button id="start" disabled>start</button>
<button id="stop" disabled>stop</button>
<script type="module">
import { MediaRecorder, register } from 'https://jspm.dev/extendable-media-recorder';
import { connect } from 'https://jspm.dev/extendable-media-recorder-wav-encoder';
const $start = document.getElementById('start');
const $stop = document.getElementById('stop');
await register(await connect());
const chunks = [];
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const mediaRecoder = new MediaRecorder(stream, { mimeType: 'audio/wav' });
mediaRecoder.addEventListener('dataavailable', ({ data }) => {
chunks.push(data);
});
mediaRecoder.addEventListener('stop', ({ data }) => {
const blob = new Blob(chunks, { type : mediaRecoder.mimeType });
console.log(blob);
});
$start.addEventListener('click', () => {
mediaRecoder.start();
$stop.addEventListener('click', () => {
$stop.disabled = true;
mediaRecoder.stop();
});
$start.disabled = true;
$stop.disabled = false;
});
$start.disabled = false;
</script>
</body>
</html>

how should I go by making a audio file converter in react

I am trying to make an audio file converter that lets a user submit a file. Then uses JavaScripts Web Audio API to convert the pitch and stretch the file. I have gotten as far as uploading the file, use file reader to onload a function that stretches and converts the pitch. Now I am trying to export that file with the changes and I can right now only download the original file but not with the changes. I dont know how to assign file = buffer because it's from another class. How should I got by making this happen?
convertFile () {
var fileInput = document.getElementById('audio-file')
var ctx = new AudioContext()
var convertFiles = document.getElementById('convert_button')
//load audio file listener
convertFiles.addEventListener("click", function() {
if (fileInput.files[0] == undefined) {
console.log("no file found")
return false
}
var reader1 = new FileReader()
reader1.onload = function(ev) {
ctx.decodeAudioData(ev.target.result). then(function(buffer){
var soundSource = ctx.createBufferSource()
soundSource.buffer = buffer
// create the stretch
soundSource.playbackRate.linearRampToValueAtTime(0.0185, ctx.currentTime)
//connect source
soundSource.connect(ctx.destination)
// convert pitch
var pitchChange = ctx.createBiquadFilter()
pitchChange.type = 'highpass'
pitchChange.frequency.value = 432
pitchChange.connect(ctx.destination)
})
}
reader1.readAsArrayBuffer(fileInput.files[0])
})
let file = fileInput.files[0]
let url = URL.createObjectURL(file)
let link = document.createElement('a')
link.href = url
link.download = file.name
link.click()
link = null
URL.revokeObjectURL(url)
}
render() {
return (
<div className="sec2">
<input type="file" id="audio-file" accept="audio/mpeg, audio/ogg, audio/*" name="file" onChange={this.uploadFile} />
<button type="button" id="convert_button" onClick={this.convertFile}>Convert to 432Hz</button>
<download onClick={this.downloadFile}>Download File</download>
</div>
)
}
}
export default ConverterSec2
I started looking into this... I fixed a couple issues such as the audio file being loaded twice. However this is work in progress answer... I haven't figure out the saving part yet.
class ConverterSec2 extends React.Component {
uploadFile = ({ target: { files } }) => {
console.log(files[0])
let data = new FormData()
data.append('file', files[0])
}
convertFile () {
var fileInput = document.getElementById('audio-file')
var ctx = new AudioContext()
var convertFiles = document.getElementById('convert_button')
//load audio file listener
if (fileInput.files[0] == undefined) {
console.log("no file found")
return false
}
var soundSource = ctx.createBufferSource();
var reader1 = new FileReader()
reader1.onload = function(ev) {
ctx.decodeAudioData(ev.target.result).then(function(buffer){
soundSource.buffer = buffer
// create the stretch
soundSource.playbackRate.linearRampToValueAtTime(0.0185, ctx.currentTime)
//connect source
soundSource.connect(ctx.destination)
// convert pitch
var pitchChange = ctx.createBiquadFilter()
pitchChange.type = 'highpass'
pitchChange.frequency.value = 432
pitchChange.connect(ctx.destination)
})
}
reader1.readAsArrayBuffer(fileInput.files[0]);
}
downloadFile() {
let fileInput = document.getElementById('audio-file')
let file = fileInput.files[0]
let url = URL.createObjectURL(file)
let link = document.createElement('a')
link.href = url
link.download = file.name
link.click()
link = null
URL.revokeObjectURL(url)
}
render() {
return (
<div className="sec2">
<input type="file" id="audio-file" accept="audio/mpeg, audio/ogg, audio/*" name="file" onChange={this.uploadFile} />
<button type="button" id="convert_button" onClick={this.convertFile}>Convert to 432Hz</button>
<button onClick={this.downloadFile}>Download File</button>
</div>
)
}
}
Live Demo

How to change qr code filename while downloading the file using html.twig and javascript

I have a qr-code button. On click, qr-code is generated and dialog to save the image format pops-up. In which the filename always comes as "qrcode.png". I have to dynamically change the filename to the name of the files from where the qr-code is generated.
Please, help. I am new to this technology.
HTML TWIG
<th data-field="QR-BTN" data-width="60px" data-orderable="false">{{ 'QR'|trans }}</th>
JAVASCRIPT
var QREXPORT = (function() {
var qrCodeExport = function (e){
e.preventDefault();
//goqr.me api url
const QRCODE_API_URL = "https://api.qrserver.com/v1/create-qr-code/?"; //Library Used
var $form = $('#modal-qr-export-offering'),
qrFormat = $("input[name='qrCodeType']:checked").val(),
jsFormData = $form.data('bs.modal'),
accessCode = jsFormData.options.accesscode;
var params = {
data: "SESSION-" + accessCode,
size: "250x250",
margin: 0,
download: 1,
format: qrFormat,
};
window.location.href = QRCODE_API_URL + $.param(params);
};
return {
init: function() {
$(document).ready(function(){
$('#radioSvg').prop('checked', true);
$('#modal-qr-export-offering').on('hidden.bs.modal', function() {
location.reload();
});
});
$(document).on('click', '.js-btn-submit-form', qrCodeExport);
}
};
})();
QREXPORT.init();
Try using the a tag with download attribute...?
const linkEl = document.createElement('a')
linkEl.href = QRCODE_API_URL + $.param(params);
linkEl.download = 'download-name-here.png'
document.body.appendChild(linkEl)
linkEl.click()
// Maybe remove the link after it worked...?
linkEl.remove()

When I'm trying to retrieve a value from php file to javascript

I am trying to get a value from php file ,php file retrieve data from ORACLE DATABASE, to a script js this is the php file :
<?php
include("../../config.php");
if(isset($_POST['songId'])) {
$songId = $_POST['songId'];
$query = oci_parse($con, "SELECT s.song_path, s.song_id, s.TITLE, r.Artist_Name, a.artworkpath FROM songs s, artists r, albums a WHERE s.artist_id = r.artist_id AND a.album_id = s.album_id AND song_id='$songId'");
oci_execute($query);
$resultArray = oci_fetch_array($query);
echo json_encode($resultArray,JSON_FORCE_OBJECT);
}
?>
it works and successfully retrieve data from the tables.
The script that uses data:
<?php
$songQuery = oci_parse($con, "SELECT song_id from songs order by dbms_random.value");
oci_execute($songQuery);
$resultArray = array();
while(($row = oci_fetch_array($songQuery, OCI_BOTH)) != false) {
array_push($resultArray, $row['SONG_ID']);
}
$jsonArray = json_encode($resultArray, JSON_FORCE_OBJECT);
?>
<script>
$(document).ready(function() {
currentPlaylist = <?php echo $jsonArray; ?>;
audioElement = new Audio();
setTrack(currentPlaylist[0], currentPlaylist, false);
});
function setTrack(trackId, newPlaylist, play) {
$.post("includes/handlers/ajax/getSongJson.php", { songId: trackId }, function(data) {
var track = JSON.parse(data);
$(".trackName span").text(track.TITLE);
$(".artistName span").text(track.ARTIST_NAME);
$(".albumLink img").attr("src", track.ARTWORKPATH);
audioElement.setTrack(track.SONG_PATH);
audioElement.audio.play();
});
if(play == true) {
audioElement.audio.play();
}
}
function playSong() {
if(audioElement.audio.currentTime == 0) {
$.post("includes/handlers/ajax/updatePlays.php", { songId: audioElement.audio.currentlyPlaying.SONG_ID});
}
$(".controlButton.play").hide();
$(".controlButton.pause").show();
audioElement.audio.play();}
function pauseSong() {
$(".controlButton.play").show();
$(".controlButton.pause").hide();
audioElement.audio.pause();
}
</script>
All the functions work well except
(songId: audioElement.audio.currentlyPlaying.SONG_ID)
It don't recognize SONG_ID which is a column from database retrieved in the php file (ajax/getSongJson.php)
PS: the (ajax/updatePlays.php) file is a php file that is for Updating DATA (PLAYS) when the user use playSong function when the current time = 0 so it increment the PLAY colomn in the database by 1
The update php file
<?php
include("../../config.php");
if(isset($_POST['songId'])) {
$songId = $_POST['songId'];
$query = OCI_parse($con, "UPDATE songs SET plays = plays + 1 WHERE song_id='$songId'");
oci_execute($query);
}
?>
This is the script file when I created a Audio Class, used in the script:
var currentPlaylist = [];
var audioElement;
function Audio() {
this.currentlyPlaying;
this.audio = document.createElement('audio');
this.setTrack = function(track) {
this.currentlyPlaying = track;
this.audio.src = track.SONG_PATH;
}
this.play = function() {
this.play();
}
this.pause = function() {
this.pause();
}
}
The error says :
Uncaught TypeError: Cannot read property 'SONG_ID' of undefined
at playSong ((index):140)
at HTMLButtonElement.onclick

Post dynamic twitter updates

I currently have some script on my page that parses title/artist information from my online radio station. I am displaying it as plain text in html by using
<span id="song_title"></span>
How can I take this dynamic information that is going into the span id and use it for a "post to twitter" link so listeners can share the current song title on Twitter?
I did some research and found a few variations on posting to twitter, but I had no luck with posting this dynamic text.
Here's the script code:
<!-- Begin Now Playing Script -->
<script>
(function () {
// we need a JSON parser, if it does not exist, load it
if (typeof JSON == "undefined") {
var s = document.createElement("script");
// json2.js retrieved from https://github.com/douglascrockford/JSON-js
s.src = "json2.js";
document.getElementsByTagName("head").appendChild(s);
}
})();
var song_ends = 0;
function update_song () {
if ((new Date).getTime() < song_ends) {
// use cached result as the song has not ended yet
return;
}
var req = new XMLHttpRequest();
// IE compatbility:
var textContent = 'textContent' in document ? 'textContent' : 'innerText';
req.onreadystatechange = function () {
if (req.readyState == 4) {
var song = JSON.parse(req.responseText);
if (song.title) {
var img = document.getElementById("song_image");
if(song.image.src){
img.alt = song.image.alt;
img.src = song.image.src;
img.width = 100;
img.height = 100;
}else{
img.src="images/default_art.png";
img.width = 100;
img.height = 100;
}
document.getElementById("song_title")[textContent] = song.title ;
document.getElementById("song_artist")[textContent] = song.artist;
document.getElementById("song_next")[textContent] = song.next ;
// store the end date in javascript date format
song_ends = (new Date).getTime() + song.wait_ms;
}
}
};
req.open('get', 'php/PlayingNow.php', true);
req.send(null);
}
// poll for changes every 20 seconds
setInterval(update_song, 20000);
// and update the song information
update_song();
</script>
<!-- End Now Playing Script -->
I want to be able to post it to Twitter like this: Currently listening to (song_title) by (song_artist)
Here is the code for the PHP file referenced in the script above:
<?php // filename: PlayingNow.php
$json = null;
$cache = 'song.json';
// if there is no usuable cache
if (!$json) {
// retrieve the contents of the URL
$ch = curl_init('http://bigcountry.streamon.fm/card');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
curl_close($ch);
$json = json_decode($res);
// if the title exists, assume the result to be valid
if ($json && $json->title) {
// cache it
$fp = fopen('song.json', 'w');
fwrite($fp, $res);
fclose($fp);
} else {
$json = null;
}
}
if ($json) {
$info = array();
// contains the time in milliseconds
$info['wait_ms'] = $json->interval->ends_at - 1000 * microtime(true);
$info['title'] = $json->title ;
$info['artist'] = $json->artist;
$info['album'] = $json->album ;
$info['next'] = $json->next_song;
$info['image'] = $json->album_art;
// display a JSON response for the HTML page
echo json_encode($info);
}
?>
The "right" way to do this is to use Twitter's Web Intents, which is designed specifically for this scenario. Take a look at the "Tweet or Reply to a Tweet" section. In practice you'll just include the Web Intents script (http://platform.twitter.com/widgets.js) on your page, create a link, and set its href, e.g.:
var link = document.createElement('a');
link.innerHTML = "Link Text";
link.href = 'http://twitter.com/intent/tweet?text=Currently listening to "' + songTitle + '" by ' + songArtist;
var parentElement = document.getElementById('SOME_ELEMENTS_ID');
parentElement.appendChild(link);
You can add the url parameter if you also want the tweet to include your site's URL.

Categories

Resources