Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从iOS向PHP发布音频文件时遇到问题_Php_Ios_Swift_Avaudiorecorder - Fatal编程技术网

从iOS向PHP发布音频文件时遇到问题

从iOS向PHP发布音频文件时遇到问题,php,ios,swift,avaudiorecorder,Php,Ios,Swift,Avaudiorecorder,我正在应用程序中录制音频(如.m4a)。那很好用。我可以制作这些数据,并将其发送到我的PHP脚本,然后上传。但是,它不再是有效的音频文件-当我从公共服务器下载时,它无法播放。下面是记录完成时的代码、带有标题的正文的生成以及我的PHP。我还提供了服务器的响应,其中显示了一些我认为需要解决但不确定的问题 func finishRecording(success: Bool) { if success { if NSData(contentsOf: audioRecor

我正在应用程序中录制音频(如.m4a)。那很好用。我可以制作这些数据,并将其发送到我的PHP脚本,然后上传。但是,它不再是有效的音频文件-当我从公共服务器下载时,它无法播放。下面是记录完成时的代码、带有标题的正文的生成以及我的PHP。我还提供了服务器的响应,其中显示了一些我认为需要解决但不确定的问题

func finishRecording(success: Bool)
{
    if success
    {
        if NSData(contentsOf: audioRecorder.url) != nil
        {
            let destUrl = URL(string: destinationURL)
            let request = NSMutableURLRequest(url: destUrl!)
            request.httpMethod = "POST"
            let param = ["firstName": "Eric", "lastName": "Dolecki", "userId": "5"]
            let boundary = "Boundary-\(NSUUID().uuidString)"
            request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

            do {
                let f = try FileHandle(forReadingFrom: audioRecorder.url)
                let data = f.readDataToEndOfFile()
                print(data) // i.e. 66505 bytes
                f.closeFile()

                // Lets send the file to the PHP script to save it.
                request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", audioDataKey: data as NSData, boundary: boundary) as Data
                let task = URLSession.shared.dataTask(with: request as URLRequest)
                {
                    data, response, error in
                    if error != nil {
                        print("error=\(String(describing: error))")
                        return
                    }

                    print("Response = \(String(describing: response))")
                    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                    print("Response data = \(responseString!)")
                }
                task.resume()
            } catch {
               ...
以下是body创建函数:

func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?,
                              audioDataKey: NSData, boundary: String) -> NSData {
    let body = NSMutableData();
    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString(string: "--\(boundary)\r\n")
            body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString(string: "\(value)\r\n")
        }
    }
    let filename = "recording.m4a"
    let mimetype = "audio/m4a"
    body.appendString(string: "--\(boundary)\r\n")
    body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
    body.append(audioDataKey as Data)
    body.appendString(string: "\r\n")
    body.appendString(string: "--\(boundary)--\r\n")
    return body
    }
}

extension NSMutableData {
    func appendString(string: String) {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        append(data!)
    }
}
以下是PHP:

<?php
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$userId = $_POST["userId"];

$target_dir = "assets";
$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) 
{
    echo "Status Okay: " . $firstName . ", " . $lastName . " : " . $userId . " " . $target_dir;

} else {
    echo "Error uploading";
}

?>
我得到的响应的内容类型为text/html,内容编码为gzip。那些不可能是好的。我认为需要解决这一问题,而不是多部分/表单数据,它应该是什么(如果这是解决方案)?PHP会覆盖已经存在的文件吗


谢谢你的时间和关注

您是否能够直接播放文件(即下载文件,并使用媒体播放器播放)?总之,你需要在你的PHP脚本中设置正确的标题。我不能播放下载的文件。标题需要是什么?请参阅。但是,您必须更改内容类型以适合您的文件类型。。你可以用谷歌搜索正确的MIME类型。@gnCupo我认为我上传的文件不正确。我想我的swift代码需要修改。我正在通过ftp下载上传的文件,无法播放。我只是想确保通过PHP上传的音频文件是有效的。我早就解决了这个问题。这与错误的音频参数有关。因此,录制后发送的文件已损坏,因此无法播放。
Connection =     (
    "Keep-Alive"
);
"Content-Encoding" =     (
    gzip
);
"Content-Length" =     (
    50
);
"Content-Type" =     (
    "text/html"
);
Date =     (
    "Wed, 22 Aug 2018 13:29:04 GMT"
);
"Keep-Alive" =     (
    "timeout=5, max=100"
);
Server =     (
    "Apache/2.2.34"
);
Vary =     (
    "User-Agent,Accept-Encoding"
);
"X-Powered-By" =     (
    "PHP/5.3.29"
);