Skip to content

Instantly share code, notes, and snippets.

@shouse
Last active June 13, 2020 02:29
Show Gist options
  • Save shouse/df1199f82c246b1d0c71 to your computer and use it in GitHub Desktop.
Save shouse/df1199f82c246b1d0c71 to your computer and use it in GitHub Desktop.
/**
* This is a library for recording audio on Android and iOS using Titanium
*
* @Class Lib/AudioRecorder
* @author steven.m.house
*/
/**
* Start it rolling
* @method init
*/
function init() {
}
/**
* Start Recording
* @method startRecording
*/
exports.startRecording = function startRecording() {
// If Android
if (OS_ANDROID) {
recordAndroid();
} else {
recordAudioIOS();
}
}
/**
* Stop Recording
* @method stopRecording
*/
exports.stopRecording = function stopRecording() {
if (OS_ANDROID) {
//recordAndroid();
} else {
//recordIOS();
}
};
/**
* Record audio for Android
* @method recordAndroid
*/
function recordAndroid() {
var audioPlayer;
win.open();
var audioRecoder = require('titutorial.audiorecoder');
log.info("[AudioRecord] audioRecoder.MPEG_4 => " + audioRecoder.MPEG_4);
function startRecording() {
audioRecoder.startRecording({
outputFormat : audioRecoder.OutputFormat_MPEG_4,
directoryName : "testdir1",
fileName : "testfile1",
maxDuration : 6000,
success : function(d) {
alert("success");
log.info("[AudioRecord] response is => " + JSON.stringify(d));
var dir = Titanium.Filesystem.getFile(Titanium.Filesystem.externalStorageDirectory, 'DCIM/test.3gp');
log.info("[AudioRecord] dir.nativePath " + dir.nativePath);
var url1 = Titanium.Filesystem.getFile(d.filepath);
log.info("[AudioRecord] url1.nativePath " + url1.nativePath);
log.info("[AudioRecord] d.filepath2 " + d.filepath2);
var audioDir = Titanium.Filesystem.getFile(Titanium.Filesystem.externalStorageDirectory, 'AudioRecorder');
log.info("[AudioRecord] audioDir.nativePath " + audioDir.nativePath);
var audioFile = Titanium.Filesystem.getFile(audioDir.nativePath, d.filepath2);
log.info("[AudioRecord] audioFile.nativePath " + audioFile.nativePath);
var t1 = Titanium.Filesystem.getFile(Titanium.Filesystem.externalStorageDirectory, "/AudioRecorder/" + d.filepath2);
log.info("[AudioRecord] t1.nativePath " + t1.nativePath);
if (audioFile.exists) {
log.info('audioFile YES! (' + audioFile.nativePath + ')');
} else {
log.info('audioFile NO!');
}
var tmpFile = Titanium.Filesystem.getFile("file://" + d.filepath);
log.info("[AudioRecord] tmpFile.nativePath " + tmpFile.nativePath);
if (tmpFile.exists) {
log.info('tmpFile YES! (' + tmpFile.nativePath + ')');
} else {
log.info('tmpFile NO!');
}
var audio_file = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory + "/AudioRecorder/" + d.filepath2);
log.info("[AudioRecord] audio_file.nativePath " + audio_file.nativePath);
audioPlayer.url = tmpFile.nativePath;
},
cancel : function(d) {
alert("cancel");
log.info("error is => " + JSON.stringify(d));
}
});
}
// audioRecoder.stopRecording();
// allowBackground: true on Android allows the player to keep playing when the app is in the background.
audioPlayer = Ti.Media.createAudioPlayer({
//url : tmpFile.nativePath,
allowBackground : true
});
exports.togglePlay = function() {
};
startStopButton.addEventListener('click', function() {
// When paused, playing returns false.
// If both are false, playback is stopped.
if (audioPlayer.playing || audioPlayer.paused) {
audioPlayer.stop();
pauseResumeButton.enabled = false;
if (Ti.Platform.name === 'android') {
audioPlayer.release();
}
} else {
audioPlayer.start();
pauseResumeButton.enabled = true;
}
});
pauseResumeButton.addEventListener('click', function() {
if (audioPlayer.paused) {
audioPlayer.start();
} else {
audioPlayer.pause();
}
});
}
/**
* Record audio for iOS
* @method recordIOS
*/
function recordIOS2() {
var recorder = Ti.Media.createAudioRecorder({
compression: Ti.Media.AUDIO_FORMAT_ULAW,
format: Ti.Media.AUDIO_FILEFORMAT_WAVE
});
}
/**
* Record audio for iOS
* @method recordAudioIOS
*/
function recordAudioIOS(_args) {
var currentSessionMode = Titanium.Media.audioSessionMode;
Titanium.Media.audioSessionMode = Ti.Media.AUDIO_SESSION_MODE_PLAY_AND_RECORD;
var recording = Ti.Media.createAudioRecorder();
// default compression is Ti.Media.AUDIO_FORMAT_LINEAR_PCM
// default format is Ti.Media.AUDIO_FILEFORMAT_CAF
// this will give us a wave file with µLaw compression which
// is a generally small size and suitable for telephony recording
// for high end quality, you'll want LINEAR PCM - however, that
// will result in uncompressed audio and will be very large in size
recording.compression = Ti.Media.AUDIO_FORMAT_ULAW;
recording.format = Ti.Media.AUDIO_FILEFORMAT_WAVE;
Ti.Media.addEventListener('recordinginput', function(e) {
log.info('Input availability changed: '+e.available);
if (!e.available && recording.recording) {
b1.fireEvent('click', {});
}
});
win.addEventListener('close',function(e) {
Titanium.Media.audioSessionMode = currentSessionMode;
});
var file;
var timer;
var sound;
function lineTypeToStr() {
var type = Ti.Media.audioLineType;
switch(type) {
case Ti.Media.AUDIO_HEADSET_INOUT:
return "headset";
case Ti.Media.AUDIO_RECEIVER_AND_MIC:
return "receiver/mic";
case Ti.Media.AUDIO_HEADPHONES_AND_MIC:
return "headphones/mic";
case Ti.Media.AUDIO_HEADPHONES:
return "headphones";
case Ti.Media.AUDIO_LINEOUT:
return "lineout";
case Ti.Media.AUDIO_SPEAKER:
return "speaker";
case Ti.Media.AUDIO_MICROPHONE:
return "microphone";
case Ti.Media.AUDIO_MUTED:
return "silence switch on";
case Ti.Media.AUDIO_UNAVAILABLE:
return "unavailable";
case Ti.Media.AUDIO_UNKNOWN:
return "unknown";
}
}
var linetype = lineTypeToStr()
var volume = Ti.Media.volume;
Ti.Media.addEventListener('linechange',function(e) {
linetype.text = "audio line type: "+lineTypeToStr();
});
Ti.Media.addEventListener('volume',function(e) {
volume.text = "volume: "+e.volume;
});
var duration = 0;
function showLevels() {
var peak = Ti.Media.peakMicrophonePower;
var avg = Ti.Media.averageMicrophonePower;
duration++;
label.text = 'duration: '+duration+' seconds\npeak power: '+peak+'\navg power: '+avg;
}
function startRecording() {
if (recording.recording) {
file = recording.stop();
b1.title = "Start Recording";
b2.show();
pause.hide();
clearInterval(timer);
Ti.Media.stopMicrophoneMonitor();
}
else {
if (!Ti.Media.canRecord) {
Ti.UI.createAlertDialog({
title:'Error!',
message:'No audio recording hardware is currently connected.'
}).show();
return;
}
b1.title = "Stop Recording";
recording.start();
b2.hide();
pause.show();
Ti.Media.startMicrophoneMonitor();
duration = 0;
timer = setInterval(showLevels,1000);
}
}
function pauseRecording() {
if (recording.paused) {
pause.title = 'Pause recording';
recording.resume();
timer = setInterval(showLevels,1000);
}
else {
pause.title = 'Unpause recording';
recording.pause();
clearInterval(timer);
}
}
function playbackRecording() {
if (sound && sound.playing)
{
sound.stop();
sound.release();
sound = null;
b2.title = 'Playback Recording';
}
else
{
log.info("recording file size: "+file.size);
sound = Titanium.Media.createSound({url:file});
sound.addEventListener('complete', function()
{
b2.title = 'Playback Recording';
});
sound.play();
b2.title = 'Stop Playback';
}
}
function toggleHiFi() {
if (recording.compression == Ti.Media.AUDIO_FORMAT_ULAW;) {
recording.compression = Ti.Media.AUDIO_FORMAT_LINEAR_PCM;
}
else {
recording.compression = Ti.Media.AUDIO_FORMAT_ULAW;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment