How To Use Media in Phonegap

Posted By : Avilash Choudhary | 12-Jun-2014

Media in Phonegap

Use of Media plugin in phonegap to record audio files. If you want to get base64 of audio file then you can use below code.

For below code to work you have to add media and file plugin in your phonegap project:

var audio = {};
// function to record audio file 
audio.recordAudio =function(){
    audioSrc = "myrecording.wav";
    audio.myMedia = new Media(audioSrc, audio.onSuccessRecord, audio.onErrorRecord);
    // Record audio
    audio.myMedia.startRecord();
};
// function to stop recording
audio.stopRecordAudio = function(){
    audio.myMedia.stopRecord();  
           // function to read file and get base64
audio.getAudioBase();
};

audio.onSuccessRecord = function() {
    console.log("recordAudio():Audio Success");
};

// onError Callback
audio.onErrorRecord = function(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
};

After recording the audio you need to use file plugin to read base64 of audio file

 
// file reading
audio.getAudioBase = function(){
window.requestFileSystem(LocalFileSystem.TEMPORARY,0,audio.gotFileSystem,audio.fileFail); 
};

In below function, you can use options such as  create:true, In that case if file is not available he will create a new file with the name you given in getFile function.

 
audio.gotFileSystem = function(fileSystem){
    fileSystem.root.getFile(“filename”,{create:false,exclusive:false}, audio.gotFileEntry, audio.fileFail);
};

audio.gotFileEntry = function(fileEntry){
    fileEntry.file(audio.gotFile,audio.fileFail);
};

audio.gotFile = function(file){
    file.type='audio/wav';
    audio.readAsDataURL(file);
};

audio.readAsDataURL = function(file){
    console.log('reading as url');
    var reader=new FileReader();
    reader.onloadend=function(evt){
        console.log("Read as data url");
          console.log(‘base64 of audio ’+evt.target.result)                  
           };
    reader.readAsDataURL(file);
};
audio.fileFail = function(error){
    console.log(error.code);
    alert("fail " +  error.code);
};

Thanks

About Author

Author Image
Avilash Choudhary

Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..