hey guys i am using the media phonegap api to play,pause and stop the audio. so far i managed to play,stop and pause, but i do not know how to resume please help me
below is the code i have written till now
var my_media = null;
var mediaTimer = null;
var pausePos = 0;
var counter=0;
var playing=false;
function playAudio(src) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
// Play audio
my_media.play();
// get audio duration
var duration = my_media.getDuration();
// set slider data
if( duration > 0 ){
$('#slider').attr( 'max', Math.round(duration) );
$('#slider').slider('refresh');
}
// Update my_media position every second
if (mediaTimer == null) {
mediaTimer = setInterval(function() {
// get my_media position
my_media.getCurrentPosition(
// success callback
function(position) {
if (position > -1) {
setAudioPosition(position);
}
},
// error callback
function(e) {
console.log("Error getting pos=" + e);
setAudioPosition("Error: " + e);
}
);
}, 1000);
}
}
/* pause audio */
function pauseAudio() {
if (my_media) {
my_media.pause();
}
}
function resumeAudio()
{
}
/* stop audio */
function stopAudio() {
if (my_media) {
my_media.stop();
playing = false;
my_media.release();
}
clearInterval(mediaTimer);
mediaTimer = null;
pausePos = 0;
}
// onSuccess Callback
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Set audio position
function setAudioPosition(position) {
pausePos = position;
position = Math.round(position);
$('#slider').val(position);
$('#slider').slider('refresh');
}
function player(id)
{
//alert(id);
playAudio("/sdcard/MuseumCache/"+id+"/"+id+".mp3");
//alert("end");
}
Please help me to write the resume function. they said the media.play() plays and resumes playing audio file
ok I fond the solution: Phonegap's Docs are terrible...badly explained
so their example is sloppy
the point is: you must not reinitialize the media everytime you play otherwise it starts form beginning
var my_media == null;
function playAudio(url) {
if (my_media === null){
// so only is your media handler is empty you initialiaze it otherwise you just play
my_media = new Media(url, function() {
console.log("Audio Success");
}, function(err) {
console.log("Audio Error");
});
}
my_media.play();
}
As per the documentation of PhoneGap media.play starts or resume the audio file.
media.play: Start or resume playing audio file.
you can find the link here
Francesco your solution work only if you have one sound to play, if you have multi sound on the same page each player will get the property of the first media...
Related
I am using recordJs library for recording voice of client and send it to the server. In firefox and other browsers, it works well without any error. when i try to run it in chrome, it starts recording the voice, but when it calls stopRecording function, it faces following error:
Uncaught TypeError: Cannot read property 'stop' of undefined
at stopRecording (توانایی-پرسش-سن-از-افراد:1209)
at startTimer (توانایی-پرسش-سن-از-افراد:1364)
Here is my JS codes:
<script type="text/javascript">
'use strict';
//webkitURL is deprecated but nevertheless
URL = window.URL || window.webkitURL;
let gumStream; //stream from getUserMedia()
let rec; //Recorder.js object
let input; //MediaStreamAudioSourceNode we'll be recording
// shim for AudioContext when it's not avb.
let AudioContext = window.AudioContext || window.webkitAudioContext;
let audioContext //audio context to help us record
function startRecording() {
console.log("recordButton clicked");
/*
Simple constraints object, for more advanced audio features see
https://addpipe.com/blog/audio-constraints-getusermedia/
*/
var constraints = { audio: true, video:false }
/*
Disable the record button until we get a success or fail from getUserMedia()
*/
/*
We're using the standard promise based getUserMedia()
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
*/
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
console.log("getUserMedia() success, stream created, initializing Recorder.js ...");
/*
create an audio context after getUserMedia is called
sampleRate might change after getUserMedia is called, like it does on macOS when recording through AirPods
the sampleRate defaults to the one set in your OS for your playback device
*/
audioContext = new AudioContext();
//update the format
// document.getElementById("formats").innerHTML="Format: 1 channel pcm # "+audioContext.sampleRate/1000+"kHz"
/* assign to gumStream for later use */
gumStream = stream;
/* use the stream */
input = audioContext.createMediaStreamSource(stream);
/*
Create the Recorder object and configure to record mono sound (1 channel)
Recording 2 channels will double the file size
*/
rec = new Recorder(input,{numChannels:1});
//start the recording process
rec.record();
console.log("Recording started");
}).catch(function(err) {
});
}
function pauseRecording(){
console.log("pauseButton clicked rec.recording=",rec.recording );
if (rec.recording){
//pause
rec.stop();
}else{
rec.record();
}
}
function stopRecording() {
//tell the recorder to stop the recording
rec.stop();
//stop microphone access
gumStream.getAudioTracks()[0].stop();
//create the wav blob and pass it on to createDownloadLink
rec.exportWAV(setUserVoice);
}
function setUserVoice(blob)
{
let formData = new FormData
formData.append('userVoice', blob)
$.ajax({
type: 'POST',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{ route('user.mockTest.participation.saveUserVoice') }}',
data: formData,
processData: false,
contentType: false,
success: function (data) {
if (data['result'] == 'success')
{
$('#recordUserVoice').prop('disabled', true);
}
else
{
Swal.fire(
'{{__('Error')}}',
'{{__('An error occurred')}}',
'error'
);
}
},
error: function (err) {
console.log(err);
}
});
}
function createDownloadLink(blob) {
var url = URL.createObjectURL(blob);
var au = document.createElement('audio');
var li = document.createElement('li');
var link = document.createElement('a');
//name of .wav file to use during upload and download (without extendion)
var filename = new Date().toISOString();
//add controls to the <audio> element
au.controls = true;
au.src = url;
//save to disk link
link.href = url;
link.download = filename+".wav"; //download forces the browser to donwload the file using the filename
link.innerHTML = "Save to disk";
//add the new audio element to li
li.appendChild(au);
//add the filename to the li
li.appendChild(document.createTextNode(filename+".wav "))
//add the save to disk link to li
li.appendChild(link);
//upload link
var upload = document.createElement('a');
upload.href="#";
upload.innerHTML = "Upload";
upload.addEventListener("click", function(event){
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("audio_data",blob, filename);
xhr.open("POST","upload.php",true);
xhr.send(fd);
})
li.appendChild(document.createTextNode (" "))//add a space in between
li.appendChild(upload)//add the upload link to li
//add the li element to the ol
recordingsList.appendChild(li);
}
document.getElementById('timer').innerHTML =
'00' + ":" + '00';
function startRecord()
{
startRecording();
startTimer();
}
function startTimer() {
$('#recordTextHolder').addClass('d-none');
$('#timer').removeClass('d-none');
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
console.log(timeArray[1])
var s = checkSecond((parseInt(timeArray[1]) + 1));
if(parseInt(s) == 5)
{
m = '0'+(parseInt(m)+1)
s = '00'
}
if(m == 2 && s == 1){
stopRecording()
shake()
return
}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers <10
if (sec < 0) {sec = "59"};
return sec;
</script>
I would be grateful, if someone guide me to handle this problem.
It looks like you are setting the value of rec here:
rec = new Recorder(input,{numChannels:1});
And the error message is presumably from here:
function stopRecording() {
//tell the recorder to stop the recording
rec.stop();
Can you try adding a console.log?
function stopRecording() {
console.log("rec:", rec)
rec.stop();
Report back what rec contains at that time.
Thanks for reporting that it says "undefined".
Now ask yourself: how can 'rec' be undefined at that time?
I assume that your console is showing the "recordButton clicked"?
And the "getUserMedia() success..."?
How about the "Recording started" message?
I suggest getting rid of the following block:
.catch(function(err) {
});
What that block does is silently "swallow" any error messages that you would otherwise see. In general, don't put in empty catch blocks unless you genuinely do not want to know about errors occurring there.
I have code that dynamically loads audio files from a directory. Right now they play/pause when a div is clicked. Here is my javascript doing that:
function get_list_of_files_from_html( html_string ){
var el = document.createElement( 'html' );
el.innerHTML = html_string;
var list_of_files = el.getElementsByTagName( 'a' );
var return_string ='<UL>';
for(var i=5; i < list_of_files.length ; i++){
var current_string = list_of_files[i];
var new_string =
current_string.toString().replace
(/http:\/\/www.website.com\/~user\/programming\//g,'');
var brand_new = new_string.replace('.mp3','');
return_string += '<div class="floating"
onclick="playAudio(\'audio_tag_id'+i+'\')" >'+brand_new+'<audio
id="audio_tag_id'+i+'"> <source src = "'+current_string+'"
type="audio/mpeg"></audio>';
return_string += '</div>';
}
return return_string;
}
function playAudio(tag_id){
var audio= document.getElementById(tag_id);
return audio.paused ? audio.play() : audio.pause();
}
I want to make a button that plays only like five seconds of each audio file and runs through them in order. Does anyone know how I would go about doing this?
You'll need to work asynchronously, so it's a ping-pong between the main code and a callback. Something like this:
// The click event handler
function onPlayClicked(event){
if (!window.HTMLAudioElement){
console.write("Error: no audio");
return;
}
// toggle the state of the playlist not the actual music player
isPlaying = !isPlaying;
if (isPlaying) startPlaying();
else resetList(); // if clicked while playing
}
// sets timer and plays current
function startPlaying(){
if (isPlaying){ // just checking that no one pressed the STOP in the meantime...
setTimout(done, 5000); // timer callback and miliseconds
playAudio();
}
}
// stops this song and starts next. Callback from timer
function done(){
if (nowPlaying == lastSongIndex(){
pauseAudio();
resetPlaylist();
return;
}
if (isPlaying){
pauseAudio();
nowPlaying++;
startPlaying();
}
// plays current audio
function playAudio(){
// Friendly advice: don't use getElementByTag. There may be other 'a's.
audioList = document.getElementById('audiolist');
audioURL = audioList[nowPlaying]; // nowPlaying advanced by done()
urlregex = '/http:\/\/www.website.com\/~user\/programming\//g';
audioData = audioUrl.remove(urlregex).replace('.mp3','');
player = document.getElementById('audioplayer');
player.src = audioData;
player.play();
}
function pauseAudio(){
player = document.getElementById('audioplayer');
player.pause();
}
function reset(){
pauseAudio();
nowPlaying = 0;
isPlaying = false;
// Unpress the button
}
// you can easily fill in the rest.
For understanding the audio control in HTML5 see this for an overview at w3schools, and this as an example on the same website.
Also note friendly remark: Javascript uses camelCase as a convention and not snake_case as in Python.
The following script is playing a soundfile when i click on a img (onclick). How do i pause it by clicking on the same img? I´ve tried audio.pause(), but it won´t work.
function play(){
var audio = document.getElementById("myaudio");
audio.style.display="block";
audio.play();
}
<img src="Bilder/play2.png">
You should rename your function to audioHandler() for example which will handle whether to play or pause your audio.
Create a boolean to remember if your audio was playing or was on pause.
//initial status: audio is not playing
var status = false;
var audio = document.getElementById("myaudio");
function audioHandler(){
if(status == false || audio.paused){
audio.play();
status = true;
}else{
audio.pause();
status = false;
}
}
Check the media.paused property of your HTMLMediaElement
function play_pause(media) {
if (media.paused) {
media.play();
else {
media.pause();
}
}
Use this in the handler on the element you want to control the action
var elm = document.getElementById('play_button'),
audio = document.getElementById('myaudio');
elm.addEventListener('click', function (e) {
play_pause(audio);
});
I have a simple mobile app designed using PhoneGap. I am some mp3 in it and I am using the Media plugin of PhoneGap. Everything is working fine, the audio is playing and so on.
The issue, I noticed after playing 8-12 times, the audio stops playing. I do not get sound. Here are my codes:
JavaScript
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
}
// Audio player
var media = null;
var audioP = false;
// Play audio
function playAudio(src) {
if (audioP === false) {
media = new Media(src, onSuccess, onError);
media.play();
audioP = true;
} else {
media.release();
}
}
// onSuccess Callback
function onSuccess() {
console.log("playAudio():Audio Success");
audioP = false;
}
// onError Callback
function onError(error) {
}
</script>
Help please!
Hi i try to add sound to my game i used aphoneGap code to do it :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Media Example</title>
<script type="text/javascript" charset="utf-8" src="js/phonegap-1.4.1.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3");
}
// Audio player
//
var my_media = null;
var mediaTimer = null;
// Play audio
//
function playAudio(src) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
// Play audio
my_media.play();
// Update my_media position every second
if (mediaTimer == null) {
mediaTimer = setInterval(function() {
// get my_media position
my_media.getCurrentPosition(
// success callback
function(position) {
if (position > -1) {
setAudioPosition((position) + " sec");
}
},
// error callback
function(e) {
console.log("Error getting pos=" + e);
setAudioPosition("Error: " + e);
}
);
}, 1000);
}
}
// Pause audio
//
function pauseAudio() {
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');
}
// Set audio position
//
function setAudioPosition(position) {
document.getElementById('audio_position').innerHTML = position;
}
</script>
</head>
<body>
<a href="#" class="btn large"
onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s_-
_rockGuitar.mp3');">Play Audio</a>
Pause Playing Audio
Stop Playing Audio
<p id="audio_position"></p>
</body>
</html>
it works fine , but when i change the source of sound it didn't work here's the code :
playAudio("file:///android_asset/www/sounds/introDino.mp3");
Any idea please,
Thank you in advance
Change your path to "/android_asset/www/sounds/introDino.mp3" and it will be fine. Read my mini tutorial for Android:
http://simonmacdonald.blogspot.com/2011/05/using-media-class-in-phonegap.html
This function will play sound using the HTML5 Audio API if available, with fallback to the PhoneGap Media API if not:
function playAudio(src) {
// HTML5 Audio
if (typeof Audio != "undefined") {
new Audio(src).play() ;
// Phonegap media
} else if (typeof device != "undefined") {
// Android needs the search path explicitly specified
if (device.platform == 'Android') {
src = '/android_asset/www/' + src;
}
var mediaRes = new Media(src,
function onSuccess() {
// release the media resource once finished playing
mediaRes.release();
},
function onError(e){
console.log("error playing sound: " + JSON.stringify(e));
});
mediaRes.play();
} else {
console.log("no sound API to play: " + src);
}
}
Due fact that Audio object on new Android versions (may be on other platforms) available and not 'undefined' both previous answers will not work. So I upgraded code to :
function playSound(src){
var devicePlatform = (typeof device !== 'undefined' && device.platform)? device.platform: null;
if (typeof Audio !== "undefined" && devicePlatform === null) { // HTML5 Audio
new Audio(src).play() ;
} else if ( devicePlatform ) { // Phonegap media
if (devicePlatform === 'Android') { // Android needs the search path explicitly specified
src = '/android_asset/www/' + src;
}
var media = new Media(src,
function onSuccess() {
media.release(); // Release the media resource once finished playing
},
function onError(e){
console.log("error playing sound: " + JSON.stringify(e));
}
);
media.play({numberOfLoops: 1});
} else {
console.log("no sound API to play: " + src);
}
}
Also must say that before all you must add to cordova build 'device' and 'media' plugins otherwise nothing will work. Plugins available here