as3 / php mp3字节数组传输和写入

时间:2012-02-02 22:07:37

标签: php actionscript-3 file mp3 bytearray

我已经在一段时间内解决了问题。

我正在制作一个儿童游戏(flash as3),其中向儿童宣读故事,诗歌,歌曲等。有一个录音/阅读文本的录音,文字突出显示单词被说/唱。孩子可以独立地切换声音和单词突出显示。孩子也可以选择自己录音。现在说录音工作正常。我能够从麦克风中捕获它,孩子可以播放它没问题。

问题在于客户希望孩子能够将此录音保存到Web服务器。

我认为通过使用URLRequest和URLLoader对象解决了问题。 mp3出现在网络服务器上的指定文件夹中。我用媒体播放器播放它,它工作。孩子也可以加载所说的文件没问题。

然后,当我通过浏览器(而不是flash播放器)尝试它时,我遇到了可怕的沙盒错误。在浏览器环境中进行所述对象操作的唯一方法是,如果用户是通过对话窗口启动的。这是孩子们在谈论的,我们无论如何都不会在当地储蓄。

为孩子提供3个他们点击的保存位置(WSprites)。从技术上讲,这是用户启动的,但闪存无法知道这一点。 3个保存槽可将声音保存在内存中,仅在用户记录或加载时更改。当用户保存时,他们会被发送到php进行保存。

现在我尝试使用js作为中间人,但我最终在这个过程中丢失了我的字节,而我的js和php可能是我所有编程技能中最薄弱的部分。

我的问题是,有没有人知道如何在不启动沙盒的情况下将字节数组发送到php。 (最好没有js,但如果我必须这样做的话)

下面是php脚本:

<?php

    $default_path = 'images/';

    // check to see if a path was sent in from flash //
    $target_path = ($_POST['dir']) ? $_POST['dir'] : $default_path;
    if (!file_exists($target_path)) mkdir($target_path, 0777, true);

    // full path to the saved image including filename //
    $destination = $target_path . basename( $_FILES[ 'Filedata' ][ 'name' ] ); 


    // move the image into the specified directory //
    if (move_uploaded_file($_FILES[ 'Filedata' ][ 'tmp_name' ], $destination)) {
      echo "The file " . basename( $_FILES[ 'Filedata' ][ 'name' ] ) . " has been uploaded;";
    } else {
        echo "FILE UPLOAD FAILED";
    }
?>

以下是与之交互的as3方法:

public function save(slotNum:uint, byteArray:ByteArray, fileName:String, 
                     $destination:String = null, $script:String=null, 
                 parameters:Object = null):void
{
//trace("this happens"); //debug                

_curRecordSlot = slotNum; //set slot number
_recorder = _recordSlots[_curRecordSlot]; //set recorder to new slot
_saveFileName = "recording" + _curRecordSlot.toString() + ".mp3"; //set recording file name         

var i: int;
var bytes:String;

var postData:ByteArray = new ByteArray();
postData.endian = Endian.BIG_ENDIAN;

var ldr:URLLoader = new URLLoader(); //instantiate a url loader
ldr.dataFormat = URLLoaderDataFormat.BINARY; //set loader format

_request = new URLRequest(); //reinstantiate request
_request.url = $script; //set path to upload script

//add Filename to parameters
if (parameters == null) 
{
    parameters = new Object();
}
parameters.Filename = fileName;

//add parameters to postData
for (var name:String in parameters) 
{
    postData = BOUNDARY(postData);
    postData = LINEBREAK(postData);
    bytes = 'Content-Disposition: form-data; name="' + name + '"';
    for ( i = 0; i < bytes.length; i++ ) 
    {
        postData.writeByte( bytes.charCodeAt(i) );
    }
    postData = LINEBREAK(postData);
    postData = LINEBREAK(postData);
    postData.writeUTFBytes(parameters[name]);
    postData = LINEBREAK(postData);
}

//add img destination directory to postData if provided //
if ($destination)
{    
    postData = BOUNDARY(postData);
    postData = LINEBREAK(postData);
    bytes = 'Content-Disposition: form-data; name="dir"';
    for ( i = 0; i < bytes.length; i++ ) 
    {
        postData.writeByte( bytes.charCodeAt(i) );
    }
    postData = LINEBREAK(postData);
    postData = LINEBREAK(postData);
    postData.writeUTFBytes($destination);
    postData = LINEBREAK(postData);
}

//add Filedata to postData
postData = BOUNDARY(postData);
postData = LINEBREAK(postData);
bytes = 'Content-Disposition: form-data; name="Filedata"; filename="';
for ( i = 0; i < bytes.length; i++ ) 
{
    postData.writeByte( bytes.charCodeAt(i) );
}
postData.writeUTFBytes(fileName);
postData = QUOTATIONMARK(postData);
postData = LINEBREAK(postData);
bytes = 'Content-Type: application/octet-stream';
for ( i = 0; i < bytes.length; i++ ) 
{
    postData.writeByte( bytes.charCodeAt(i) );
}
postData = LINEBREAK(postData);
postData = LINEBREAK(postData);
postData.writeBytes(byteArray, 0, byteArray.length);
postData = LINEBREAK(postData);

//add upload file to postData
postData = LINEBREAK(postData);
postData = BOUNDARY(postData);
postData = LINEBREAK(postData);
bytes = 'Content-Disposition: form-data; name="Upload"';
for ( i = 0; i < bytes.length; i++ ) 
{
    postData.writeByte( bytes.charCodeAt(i) );
}
postData = LINEBREAK(postData);
postData = LINEBREAK(postData);
bytes = 'Submit Query';
for ( i = 0; i < bytes.length; i++ ) 
{
    postData.writeByte( bytes.charCodeAt(i) );
}
postData = LINEBREAK(postData);

//closing boundary
postData = BOUNDARY(postData);
postData = DOUBLEDASH(postData);        

//finally set up the urlrequest object //
_request.data = postData;
_request.contentType = 'multipart/form-data; boundary=' + _boundary;
_request.method = URLRequestMethod.POST;
_request.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );

//add listener to listen for completion
      ldr.addEventListener(Event.COMPLETE, onSaveComplete, false, 0, true); 
//add listener for io errors
      ldr.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler, false, 0, true);
//add listener for security errors
      ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError, false, 
                           0, true);
ldr.load(_request); //load the file 
}

以上代码在Flash播放器中运行良好,但在浏览器中触发了沙箱错误。

编辑:

这里要求的是我的嵌入代码(我替换了任何有TITLEOFGAME游戏名称的地方):

<html lang="en">
<head>
<meta charset="utf-8"/>
<title>TITLEOFGAME</title>
<meta name="description" content="" />

<script src="js/swfobject.js"></script>
<script>
    var flashvars = {
    };
    var params = {
        menu: "false",
        scale: "noScale",
        allowFullscreen: "true",
        allowScriptAccess: "always",
        bgcolor: "",
        wmode: "direct" // can cause issues with FP settings & webcam
    };
    var attributes = {
        id:"TITLEOFGAME"
    };
    swfobject.embedSWF(
        "Hub.swf", 
        "altContent", "900", "506", "10.0.0", 
        "expressInstall.swf", 
        flashvars, params, attributes,
        {name:"TITLEOFGAME"}
    );
</script>       

<style>
    html, body { height:100%; overflow:hidden; }
    body { margin:0; }
</style>
</head>
<body>
<div id="altContent">
    <h1>TITLEOFGAME</h1>
    <p><a href="http://www.adobe.com/go/getflashplayer">Get Adobe Flash 
                player</a></p> //this line was just moved down for limitations text input for 
                               //this post
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

This has been asked before

似乎它可能是内容类型或丢失堆栈中的鼠标事件。

显然只有在URLLoader POST在Content-Disposition标题中包含'filename'属性时才会发生这种情况。
bytes = 'Content-Disposition: form-data; name="Filedata"; filename="'; 尝试使用base64编码并作为字符串发送以解决它。

[编辑]
我的猜测是违规代码。

bytes = 'Content-Disposition: form-data; name="Filedata"; filename="';
for ( i = 0; i < bytes.length; i++ ) 
{
    postData.writeByte( bytes.charCodeAt(i) );
}

如果您有包含表单数据和文件名的Content-Disposition,则会触发安全错误 其中包含文件的表单数据只能通过堆栈中的用户交互(IE:鼠标单击)发送 据说你需要删除Content-Disposition:form-data; NAME = “Filedata上”; filename =“'并用字符串替换它 我个人会抓这个方法。显然,开发人员没有在生产环境中测试此代码。

// disclaimer none of this code is tested as I pretty much just wrote it.
// however it should at least compile and you should be able to get a little idea of whats going on

// first create the endoder
var encoder:Base64Encoder = new Base64Encoder( )

// now encode the bytearray
    encoder.encodeBytes( byteArrayToEncode )

// get the encoded data as a string
var myByteArrayString:String = encoder.toString()

// lets verify the data should see a sting with base64 characters
trace( "show me the string->" + myByteArrayString )

// create the variables object that we want to POST to the server
var urlVars:URLVariables = new URLVariables();

// assign the base64 encoded bytearray to the POST variable of your choice here is use "data"
    urlVars.data = myByteArrayString;

// create the request object with the url you are sending the data to
var request:URLRequest = new URLRequest( 'Url of the PHP page below' ); 

// assign the POST data to the request
    request.data = urlVars

// just making sure POST method is being used
    request.method = URLRequestMethod.POST;

// here we make a loader even though it is a loader it can be used to send POST data along with the request to a page to load
var urlLoader:URLLoader = new URLLoader();

// just making sure the server knows we are sending data as a string
    urlLoader.dataFormat = URLLoaderDataFormat.TEXT;

// create your call back functions of your choice
 //   urlLoader.addEventListener(Event.COMPLETE, recievedData );
 //   urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler );
 //   urlLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler );

// wrap the load in a try catch because we are special
try {
// load the request object we just created
  urlLoader.load( request );
} catch (e:Error) {
  trace(e);
}

跟踪应该输出类似这样的东西dG8gQ29udmVydA ==除非字符串末尾的等号更长,所以这应该给你一个关于数据是否正确转换的提示。注意字符串是如何都是字母数字字符 既然你是byteArray的新手,我建议今晚在你的空闲时间进行一些谷歌搜索,并尝试了解它是什么以及它是如何工作的。

<?php

$decodedData= null;

if (!empty($_POST['data'])){
  // here is your data in pre-encoded format do what you want with it
  $decodedData= base64_decode( $_POST['data'] );
  file_put_contents("test.txt",$decodedData);

}

?>

答案 1 :(得分:0)

您可以将记录的数据作为字节数组发送到服务器端应用程序,Byte aaray将按照所需格式保存,如flv或任何其他文件(仅支持格式)。请使用PHP&amp; amp;检查AMFPHP,PHP和Byte数组保存。 ActionScript 3.0。你会得到它的例子。 请查看此链接以重新编码和转换字节数组中的音频:Click Here