【发布时间】:2015-03-07 22:19:44
【问题描述】:
我正在用 Swift 制作一个应用程序来录制一些音频,然后将录音发送到我的 PHP 服务器。
应用程序可以很好地录制音频片段(可以毫无问题地播放)。当我println 录制的音频剪辑时,它会显示字节数据的负载和负载(当我将音频放入NSData 包装器时也是如此)。这一切都表明应用程序内的音频很好。
在我的服务器上捕获记录的 PHP 文件也可以正常工作并且没有错误。
但是在某处录制的音频片段丢失了。
上传录音的 Swift 代码:
// The variable "recordedFileURL" is defined earlier in the code like this:
currentFilename = "xxxx.m4a"
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsDir: AnyObject=dirPaths[0]
recordedFilePath = docsDir.stringByAppendingPathComponent(self.currentFilename)
recordedFileURL = NSURL(fileURLWithPath: self.recordedFilePath)
// "currentFilename", "recordedFilePath" and "recordedFileURL" are all global variables
// This recording stored at "recordedFileURL" can be played back fine.
let sendToPath = "http://......../catch.php"
let sendToURL = NSURL(string: sendToPath)
let recording: NSData? = NSData(contentsOfURL: recordedFileURL)
let boundary = "--------14737809831466499882746641449----"
let contentType = "multipart/form-data;boundary=\(boundary)"
var request = NSMutableURLRequest()
request.URL = sendToURL
request.HTTPMethod = "POST"
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
request.addValue(recId, forHTTPHeaderField: "REC-ID") // recId is defined elsewhere
var body = NSMutableData()
var header = "Content-Disposition: form-data; name=\"\(currentFilename)\"; filename=\"\(recordedFilePath)\"\r\n"
body.appendData(("\r\n-\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData((header as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(("Content-Type: application/octet-stream\r\n\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(recording!) // adding the recording here
body.appendData(("\r\n-\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
println("upload complete")
let dataStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataStr)
})
task.resume()
文件catch.php中应该接收录音的PHP代码:
$contents = file_get_contents('php://input');
$files = $_FILES;
echo "Caught the following:/r/n";
echo "Contents:" . var_export($contents) . "/r/n";
echo "Files:" . var_export($files) . "/r/n";
每当我运行所有这些时,我都会从catch.php 得到以下输出:
Caught the following:
Contents:''
Files:array (
)
所以catch.php 根本没有收到任何东西。
是我发送录音错误,还是捕捉录音错误?还是两者兼有?
提前致谢。
【问题讨论】:
-
您确定
recording变量在您创建body.appendData(recording!)时包含数据吗?在调试器中检查它或将长度放入 NSLog 以确保... -
你检查过 php.ini 中的 max_upload_size。如果您尝试上传大于该值的文件可能会导致此问题
-
感谢您的回复! php.ini max_upload_size 设置为 20Mb(对于我们 1-10 秒的记录来说应该足够了)——是的,记录变量包含大量数据——当我 NSLog 时,调试窗口中充满了数据——它太多了,我必须滚动浏览它
-
var_dump($contents);对您有帮助吗? -
"body.appendData(("\r\n!!-!!(boundary)\r\n" - 额外的"-"这里