如何在Titanium上传我录制的音频?

时间:2014-10-07 18:04:15

标签: php audio file-upload titanium titanium-mobile

我正在尝试上传录制的音频,但我总是在服务器端获得一个空文件...

这是我的录音代码:

    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) {
    Ti.API.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;


var label = Titanium.UI.createLabel({
    text:'',
    top:150,
    color:'#999',
    textAlign:'center',
    width:'auto',
    height:'auto'
});

win.add(label);

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 = Titanium.UI.createLabel({
    text: "audio line type: "+lineTypeToStr(),
    bottom:20,
    color:'#999',
    textAlign:'center',
    width:'auto',
    height:'auto'
});

win.add(linetype);

var volume = Titanium.UI.createLabel({
    text: "volume: "+Ti.Media.volume,
    bottom:50,
    color:'#999',
    textAlign:'center',
    width:'auto',
    height:'auto'
});

win.add(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;
}

var b1 = Titanium.UI.createButton({
    title:'Start Recording',
    width:200,
    height:40,
    top:20
});
b1.addEventListener('click', function()
{
    if (recording.recording)
    {
        file = recording.stop(); 

        var f = Ti.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'recording.wav');

        if ( f.exists() ){
            f.deleteFile();
        }

        f.write( file );

        var audio = Ti.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'recording.wav');
        audio.read();

        var teste = file.toBlob();

        /*
        var emailDialog = Ti.UI.createEmailDialog();
        emailDialog.subject = "feed back brasil";
        emailDialog.toRecipients = [ 'douglas_b_h@hotmail.com' ];
        emailDialog.messageBody = 'aaaa';
        emailDialog.addAttachment( audio );
        emailDialog.open();
        */


        var xhr = Titanium.Network.createHTTPClient();

          xhr.onerror = function(e)
      {
        Ti.UI.createAlertDialog({title:'Error', message:e.error}).show();
        Ti.API.info('IN ERROR ' + e.error);
      };
      xhr.setTimeout(20000);
      xhr.onload = function(e)
      {
        //Ti.UI.createAlertDialog({title:'Success', message:'status code ' + this.status}).show();
        //Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
        Ti.API.info( this.responseText );

        Ti.API.info( audio );
      };
      xhr.onsendstream = function(e)
      {
        Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
      };

      // open the client
      xhr.open('POST','http://universopositivo.com.br/zo/pegaFileEnviaEmail.php?userfile=' + audio );
      xhr.setRequestHeader("Content-Type", "multipart/form-data");

      // send the data
      xhr.send();

        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);
    }
});
win.add(b1);

var pause = Titanium.UI.createButton({
    title:'Pause recording',
    width:200,
    height:40,
    top:80
});
win.add(pause);
pause.hide();

pause.addEventListener('click', function() {
    if (recording.paused) {
        pause.title = 'Pause recording';
        recording.resume();
        timer = setInterval(showLevels,1000);
    }
    else {
        pause.title = 'Unpause recording';
        recording.pause();
        clearInterval(timer);
    }
});

var b2 = Titanium.UI.createButton({
    title:'Playback Recording',
    width:200,
    height:40,
    top:80
});

win.add(b2);
b2.hide();
b2.addEventListener('click', function()
{
    if (sound && sound.playing)
    {
        sound.stop();
        sound.release();
        sound = null;
        b2.title = 'Playback Recording';
    }
    else
    {
        Ti.API.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';
    }
});

var switchLabel = Titanium.UI.createLabel({
    text:'Hi-fidelity:',
    width:'auto',
    height:'auto',
    textAlign:'center',
    color:'#999',
    bottom:115
});
var switcher = Titanium.UI.createSwitch({
    value:false,
    bottom:80
});

switcher.addEventListener('change',function(e)
{
    if (!switcher.value)
    {
        recording.compression = Ti.Media.AUDIO_FORMAT_ULAW;
    }
    else
    {
        recording.compression = Ti.Media.AUDIO_FORMAT_LINEAR_PCM;
    }
});
win.add(switchLabel);
win.add(switcher);

这是我的PHP接收我的数据并将其发送到电子邮件:

<?php 

    $mailto = "mailto@mailto.com";
    $subject = "teste";
    $message = "mensagem teste";

    print_r( $_FILES );

    $file = $_FILES['userfile']['name'];
    $file_size = $_FILES['userfile']['size'];
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));

    // a random hash will be necessary to send mixed content
    $separator = md5(time());

    // carriage return type (we use a PHP end of line constant)
    $eol = PHP_EOL;

    // main header (multipart mandatory)
    $headers = "From: FeedBack Team <feedbackMail@feedback.com.br>" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol . $eol;

    // message
    $headers .= "--" . $separator . $eol;
    $headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
    $headers .= $message . $eol . $eol;

    // attachment
    $headers .= "--" . $separator . $eol;
    $headers .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: base64" . $eol;
    $headers .= "Content-Disposition: attachment" . $eol . $eol;
    $headers .= $content . $eol . $eol;
    $headers .= "--" . $separator . "--";

    //SEND Mail

    if (mail($mailto, $subject, "", $headers)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
    }

?>

我认为我没有正确上传录制的音频。 有人可以帮我上传录制的音频吗? 我正在使用Titanium 3.4.0 GA并开发到iOS和Android 感谢

0 个答案:

没有答案