I am able to capture audio and I have the full path to the captured file, but I am having trouble getting it to play the most recent captured file.
I am using Phongap 2.5 and also Jquery Mobile on iOS 6.1.
Code:
<script type="text/javascript" charset="utf-8">
function captureSuccess(mediaFiles) {
var i, len;
var formatSuccess = function (mediaFile) {
document.getElementById('capture-data').innerHTML =
"Duration: <strong>" + mediaFile.duration + "</strong><br/>";
};
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
// uploadFile(mediaFiles[i]);
document.getElementById('capture-result').innerHTML = "<strong>" + (i+1) + " file(s), Path: " + mediaFiles[i].fullPath + "</strong><br/>";
mediaFiles[i].getFormatData(formatSuccess, formatError);
readDataUrl = mediaFiles[i].fullPath;
};
console.log("captureImageSuccess");
}
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
function captureAudio() {
// Launch device audio recording application,
// allowing user to capture up to 2 audio clips
navigator.device.capture.captureAudio(captureSuccess, captureError, {limit: 2});
}
$("#audio-result").click(function() {
function playAudio(mediaFiles) {
var play = document.getElementById('audio-result').src =
mediaFiles[i].fullPath;
}
});
</script>
</head>
<body>
<button onclick="captureAudio();">Capture Audio</button> <br>
<div class="result-block">
Capture Result: <span id="capture-result"></span><br/>
<span id="capture-data"></span><br/>
<button id="audio-result">Play audio</button>
</div>
</body>
</html>
you can play your media as below
var my_media = null;
// here src is the uri of your media
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
// Play audio
my_media.play()
// Pause audio
function pauseAudio() {
if (my_media) {
my_media.pause();
}
}
// Stop audio
function stopAudio() {
if (my_media) {
my_media.stop();
}
}
Related
I use Amit Agarwal code from https://www.labnol.org/internet/light-youtube-embeds/27941/ in my website to lite embeded youtube video.
Is there any way to add start time to the script so that I could load each video with different start time.
<div class="youtube-player" data-id="VIDEO_ID" start-id="TIME"></div>
His complete script are as follows:
<script>
function labnolIframe(div) {
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?autoplay=1&rel=0');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', '1');
iframe.setAttribute('allow', 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture');
div.parentNode.replaceChild(iframe, div);
}
function initYouTubeVideos() {
var playerElements = document.getElementsByClassName('youtube-player');
for (var n = 0; n < playerElements.length; n++) {
var videoId = playerElements[n].dataset.id;
var div = document.createElement('div');
div.setAttribute('data-id', videoId);
var thumbNode = document.createElement('img');
thumbNode.src='//i.ytimg.com/vi/ID/hqdefault.jpg'.replace('ID', videoId);
div.appendChild(thumbNode);
var playButton = document.createElement('div');
playButton.setAttribute('class', 'play');
div.appendChild(playButton);
div.onclick = function () {
labnolIframe(this);
};
playerElements[n].appendChild(div);
}
}
document.addEventListener('DOMContentLoaded', initYouTubeVideos);
</script>
I have added timeId var into the mix hoping that I could use start-id value to let embed video to start at specific time. It still start at 0 sec of the video.
function labnolIframe(div) {
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?start='+ div.dataset.id + '&autoplay=1&rel=0');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', '1');
iframe.setAttribute('allow', 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture');
div.parentNode.replaceChild(iframe, div);
}
function initYouTubeVideos() {
var playerElements = document.getElementsByClassName('youtube-player');
for (var n = 0; n < playerElements.length; n++) {
var videoId = playerElements[n].dataset.id;
var timeId = playerElements[n].dataset.id;
var div = document.createElement('div');
div.setAttribute('data-id', videoId);
div.setAttribute('start-id', timeId);
var thumbNode = document.createElement('img');
thumbNode.src = '//i.ytimg.com/vi/ID/hqdefault.jpg'.replace('ID', videoId);
div.appendChild(thumbNode);
var playButton = document.createElement('div');
playButton.setAttribute('class', 'play');
div.appendChild(playButton);
div.onclick = function () {
labnolIframe(this);
};
playerElements[n].appendChild(div);
}
}
document.addEventListener('DOMContentLoaded', initYouTubeVideos);
Just change:
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?autoplay=1&rel=0');
to:
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?start=YOUR_START_TIME_IN_SECONDS&autoplay=1&rel=0');
Note the added start=YOUR_START_TIME_IN_SECONDS& in the URL.
I have been following this tutorial and it succesfully renders video on to a cube using webGL.
Is it possible for instead of using a video I would like to use a live feed from a webcam without using frameworks like Three.js?
The code below reads from the webcam into HTMLVideoElement how to convert it into texture so I can map it to my vertices in raw WebGL?
function setupVideo(url) {
const video = document.createElement('video');
var playing = false;
var timeupdate = false;
video.autoplay = true;
video.muted = true;
video.loop = true;
// Waiting for these 2 events ensures
// there is data in the video
video.addEventListener('playing', function() {
playing = true;
checkReady();
}, true);
video.addEventListener('timeupdate', function() {
timeupdate = true;
checkReady();
}, true);
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
var hasUserMedia = navigator.getUserMedia ? true : false;
console.log(hasUserMedia);
// Prefer camera resolution nearest to 1280x720.
var constraints = { audio: true, video: { width: 640, height: 360 } };
navigator.mediaDevices.getUserMedia(constraints)
.then(function(mediaStream) {
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end.
video.play();
function checkReady() {
if (playing && timeupdate) {
copyVideo = true;
}
}
return video;
}
I have been trying to store Audio file in persistent storage for two days without success.
So far I am able to create an audio file which records audio from Microphone (The app has the permission) using the code attached below.
The audio file is getting generated & stored successfully, I can play it.
But the real problem is when I close the app and come back and try to play the file it shows error.
"{"message": "Cannot use audio file from resource '/myrecording.wav'",
"code":1}"
The file is not persistent across app sessions even though I used LocalFileSystem.PERSISTENT.
I am not sure whether the problem is with my Media/Audio code or File storage code.
Please find the code attached below:
Below function records the audio from the microphone.
function _recordAudio() {
var deferred = $q.defer();
var src = "myrecording.wav";
alert("SRC:" + src);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(src, {
create: true,
exclusive: false
}, function (fileEntry) {
alert("File " + src + " created at " + fileEntry.fullPath);
var mediaRec = new Media(fileEntry.fullPath,
function () {
alert("Success");
}, function (error) {
alert("error:" + JSON.stringify(error));
});
// Record audio
mediaRec.startRecord();
// Stop recording after 10 sec
var recTime = 0;
var recInterval = setInterval(function () {
recTime = recTime + 1;
if (recTime >= 5) {
clearInterval(recInterval);
mediaRec.stopRecord();
deferred.resolve(fileEntry.fullPath);
}
}, 1000);
}, function (error) {
alert("getFile error:" + JSON.stringify(error));
deferred.reject();
}); //of getFile
}, function (error) {
alert("requestFileSystem error:" + JSON.stringify(error));
deferred.reject();
}); //of requestFileSystem
return deferred.promise;
}
Below function plays the audio.
function _play2() {
var src = "myrecording.wav";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(src, null, function (fileEntry) {
alert("File " + src + " created at " + fileEntry.fullPath);
var mediaRec = new Media(fileEntry.fullPath,
function () {
alert("Success play2");
}, function (error) {
//Getting error after closing and opening the app
//Error message = {"message": "Cannot use audio file from resource '/myrecording.wav'","code":1}
alert("error play2:" + JSON.stringify(error));
});
mediaRec.play();
});
});
}
I solved this problem by passing cdvfile: path to the Media plugin in PlayAudio function code and copying the file from Temp storage to persistent storage.
I had to use localURL of the file.
This part solved my problem:
fileEntry.file(function (file) {
_playNow(file.localURL);
}
For full functions refer code snippets below:
recordAudio: function (projectNo, ItemNo) {
try {
var deferred = $q.defer();
var recordingTime = 0;
_audioLoader = $("#audioLoader");
_audioLoader.show();
UtilityService.showPopup('audio');
_isRecording = true;
_recordFileName = "Audio_" + projectNo + "_" + ItemNo + ".wav";
_mediaRecord = new Media(_recordFileName);
//Record audio
_mediaRecord.startRecord();
var recordingInterval = setInterval(function () {
recordingTime = recordingTime + 1;
$('#audioPosition').text(_secondsToHms(recordingTime));
if (!_isRecording) {
clearInterval(recordingInterval);
_mediaRecord.stopRecord();
_mediaRecord.release();
deferred.resolve();
}
}, 1000);
//document.getElementById('audioPosition').innerHTML = '0 sec';
$('#audioPosition').text('0 sec');
return deferred.promise;
}
catch (ex) {
alert('WMMCPA|recordAudio:- ' + ex.message);
}
},
Get file path from the persistent storage and send it to the play method.
//To play recorded audio for specific project item
playAudio: function (projectNo, ItemNo) {
try {
_recordFileName = "Audio_" + projectNo + "_" + ItemNo + ".wav";
var newFileUri = cordova.file.dataDirectory + _recordFileName;
window.resolveLocalFileSystemURL(newFileUri, function (fileEntry) {
fileEntry.file(function (file) {
_playNow(file.localURL);
}, function (error) {
alert("WMMCPA|playAudio.file:-" + JSON.stringify(error));
});
}, function (error) {
alert("WMMCPA|playAudio.resolveLocalFileSystemURL:-" + JSON.stringify(error));
});
}
catch (ex) {
alert("WMMCPA|playAudio:-" + ex.message);
}
}
function _playNow(src) {
try {
var mediaTimer = null;
_audioLoader = $("#audioLoader");
_audioLoader.show();
UtilityService.showPopup('audio');
//Create Media object from src
_mediaRecord = new Media(src);
//Play audio
_mediaRecord.play();
} catch (ex) {
alert('WMMCPA|_playNow.mediaTimer:- ' + ex.message);
}
}, 1000);
} catch (ex) {
alert('WMMCPA|_playNow:- ' + ex.message);
I am using media plugin to play local audio files (inside /www folder). This perfectly works in android but in iOS the error "Cannot play the audio file from resource…." is coming.
Please check the below screenshot and coding. How should i solve this to play local audio files.
<script type="text/javascript">
function getPhoneGapPath() {
'use strict';
var path = window.location.pathname;
var phoneGapPath = path.substring(0, path.lastIndexOf('/') + 1);
return phoneGapPath;
};
// Audio player
var my_media = null;
var mediaTimer = null;
// Play audio
function playAudio() {
if (my_media == null) {
// Create Media object from src
my_media = new Media(getPhoneGapPath() +'button-click.wav', onSuccess, onError);
} // else play current audio
// Play audio
my_media.play();
}
// Pause audio
//
if (my_media) {
my_media.pause();
}
}
// Stop audio
function stopAudio() {
if (my_media) {
my_media.stop();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
// onSuccess Callback
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
I've searched all the whole Internet to find a solution to my problem, but I didn't find it :(
So, I'm doing a SoundBoard app using Phonegap and Xcode and my problem is about stopping the sound from the same button I used to play the audio, but I can't do it, I think it's impossible for me!
This is a part of the Javascript with the Play and Stop functions and IsPlaying function, that I created trying to determine if the sound is playing or not using the variable SoundPlaying:
<script type="text/javascript" charset="utf-8">
SoundPlaying = false
...
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function() { console.log("playAudio():Audio Success");},
// error callback
function(err) { console.log("playAudio():Audio Error: "+err);});
// Play audio
my_media.play();
}
// Stop audio
//
function stopAudio() {
if (my_media) {
my_media.stop();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
function IsPlaying(url) {
if (SoundPlaying==false) { playAudio(url); SoundPlaying=true; alert('SoundPlaying is ' + SoundPlaying); }
else { stopAudio(); SoundPlaying=false; alert('SoundPlaying is ' + SoundPlaying); }
}
</script>
And then I tried to call the IsPlaying function from a button: if the variable SoundPlaying is false then play the sound and set SoundPlaying as true, ELSE stop the sound and set SoundPlaying as false
<button id='button'
style="background-image:url(imgs/image.png);"
onClick = "IsPlaying('msk/sound.mp3');" >
</button>
It's like the ELSE part of the statement isn't checked, but the IF part yes. Indeed i can see the alert window saying that SoundPlaying is true but not if I click on the button a second time....or a third...and so on.
Can you please help me??
Thank you very much!
Vittorio
I think you are going to deep into the code ...
What do you think about this solution?
// Audio player
//
var soundfile = null;
// Play audio
//
function playPauseAudio(src) {
if (soundfile == null) {
// Create Media object from src
soundfile = new Media(src, onSuccessAudio, onErrorAudio);
soundfile.play();
} else {
soundfile.stop();
soundfile = null;
}
}
// Callback
function onSuccessAudio(){};
function onErrorAudio(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
i used this one in my phonegap project, works great. I even with a pause button:
<script type="text/javascript">
function hide(elementID)
{
document.getElementById(elementID).style.display = 'none';
}
function show(elementID)
{
document.getElementById(elementID).style.display = '';
}
</script>
<img id="off" src="images/general/sound-off.png" width="40" height="32" onClick="show('on'); hide('off'); playAudio();" alt="on">
<img id="on" src="images/general/sound-on.png" width="40" height="32" onClick="show('pause'); hide('on'); pauseAudio();" style="display:none;" alt="off">
<img id="pause" src="images/general/sound-pause.png" width="40" height="32" onClick="show('on'); hide('pause'); playAudio();" style="display:none;" alt="on">
For the audio, i use the playaudio(), pauseaudio() and stopaudio() command in the onclick.
Hope this helps :-)