菜鸟教程小白 发表于 2022-12-11 18:18:31

ios - NSUrlRequest 在模拟器中有效,但在 iPhone 上无效


                                            <p><p>我有一个应用程序,它记录麦克风的声音,然后通过 NSUrlRequest 将其发送到我的网站。为了测试它,我添加了从网站播放的音频,这样我就可以听到它是否有效。 <br/>
当我在模拟器上测试它时,一切正常:录制并上传了音频,我可以听到它,但是当我将它安装到我的 iPhone 上时,我什么也听不见,而且在我的网站上,音频文件损坏了。</p >

<p>我的 TestNahravani.swift 代码:</p>

<pre><code>import UIKit
import AVFoundation

class TestNahravani: UIViewController, AVAudioRecorderDelegate, AVAudioPlayerDelegate {


@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var playButton: UIButton!

var soundRecorder: AVAudioRecorder!
var soundPlayer:AVAudioPlayer?

let fileName = &#34;demo.m4a&#34;

override func viewDidLoad() {
    super.viewDidLoad()
    setupRecorder()
}

@IBAction func recordSound(sender: UIButton) {
    if (sender.titleLabel?.text == &#34;Record&#34;){
      soundRecorder.record()
      sender.setTitle(&#34;Stop&#34;, for: .normal)
      playButton.isEnabled = false
    } else {
      soundRecorder.stop()
      sender.setTitle(&#34;Record&#34;, for: .normal)
    }
}

@IBAction func playSound(sender: UIButton) {
    if (sender.titleLabel?.text == &#34;Play&#34;){
      recordButton.isEnabled = false
      sender.setTitle(&#34;Stop&#34;, for: .normal)
      preparePlayer()
    } else {
      soundPlayer?.stop()
      sender.setTitle(&#34;Play&#34;, for: .normal)
    }
}

// MARK:- AVRecorder Setup

func setupRecorder() {

    //set the settings for recorder

    let recordSettings = [AVSampleRateKey : NSNumber(value: Float(44100.0)),
                        AVNumberOfChannelsKey : NSNumber(value: 2),
                        AVEncoderAudioQualityKey : NSNumber(value: Int32(AVAudioQuality.max.rawValue)),
                        AVFormatIDKey : NSNumber(value: kAudioFormatMPEG4AAC)]
    var error: NSError?
    do {
      soundRecorder =try AVAudioRecorder(url: getFileURL() as URL, settings: recordSettings)
    } catch let error1 as NSError {
      error = error1
      soundRecorder = nil
    }

    if let err = error {
      print(&#34;AVAudioRecorder error: \(err.localizedDescription)&#34;)
    } else {
      soundRecorder.delegate = self
      soundRecorder.prepareToRecord()
    }
}

// MARK:- Prepare AVPlayer

func preparePlayer() {
    var errorX: NSError?




      let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
      let docsDir: AnyObject=dirPaths as AnyObject
      var recordedFilePath : String = docsDir.appendingPathComponent(fileName)
      let recordedFileURL = getFileURL()

      // &#34;currentFilename&#34;, &#34;recordedFilePath&#34; and &#34;recordedFileURL&#34; are all global variables

      // This recording stored at &#34;recordedFileURL&#34; can be played back fine.

      let sendToPath = &#34;http://www.kvetinac97.cz/jt.php&#34;
      let sendToURL = NSURL(string: sendToPath)
      let recording: NSData! = NSData(contentsOf: recordedFileURL as URL)
    if recording == nil {
      recordedFilePath = &#34;FailedUpload&#34;
    }
      let boundary = &#34;--------14737809831466499882746641449----&#34;
      let contentType = &#34;multipart/form-data;boundary=\(boundary)&#34;

      let beginningBoundary = &#34;--\(boundary)&#34;
      let endingBoundary = &#34;--\(boundary)--&#34;

      let header = &#34;Content-Disposition: form-data; name=\&#34;\(fileName)\&#34;; filename=\&#34;\(recordedFilePath)\&#34;\r\n&#34;

      let body = NSMutableData()
      body.append((&#34;\(beginningBoundary)\r\n&#34; as NSString).data(using: String.Encoding.utf8.rawValue)!)
      body.append((header as NSString).data(using: String.Encoding.utf8.rawValue)!)
      body.append((&#34;Content-Type: application/octet-stream\r\n\r\n&#34; as NSString).data(using: String.Encoding.utf8.rawValue)!)
      body.append(recording! as Data) // adding the recording here
      body.append((&#34;\r\n\(endingBoundary)\r\n&#34; as NSString).data(using: String.Encoding.utf8.rawValue)!)

      let request = NSMutableURLRequest()
      request.url = sendToURL! as URL
      request.httpMethod = &#34;POST&#34;
      request.addValue(contentType, forHTTPHeaderField: &#34;Content-Type&#34;)
      request.addValue(&#34;multipart/form-data&#34;, forHTTPHeaderField: &#34;Accept&#34;)
      request.httpBody = body as Data

      let session = URLSession.shared
      let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -&gt; Void in
            if let data = NSData(contentsOf: NSURL(string: &#34;http://www.kvetinac97.cz/uploads/demo.m4a&#34;)! as URL) {
                do {
                  try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                  try AVAudioSession.sharedInstance().setActive(true)
                  self.soundPlayer = try AVAudioPlayer(data: data as Data, fileTypeHint: AVFileType.m4a.rawValue)
                  self.soundPlayer!.delegate = self
                  self.soundPlayer!.prepareToPlay()
                  self.soundPlayer!.volume = 1.0
                  self.soundPlayer!.play()
                } catch let error1 as NSError {
                  errorX = error1
                  self.soundPlayer = nil
                  print (&#34;Chyba nejaka \(error1)&#34;)
                }
            }
            else {
                print (&#34;Smulicka&#34;)
            }
      })
      task.resume()


}

func generateBoundaryString() -&gt; String {
    return &#34;Boundary-\(NSUUID().uuidString)&#34;
}

// MARK:- File URL

func getCacheDirectory() -&gt; String {

    let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory,.userDomainMask, true)

    return paths
}

func getFileURL() -&gt; NSURL {

    let path = getCacheDirectory().appending(fileName)

    let filePath = NSURL(fileURLWithPath: path)

    return filePath
}

// MARK:- AVAudioPlayer delegate methods

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    recordButton.isEnabled = true
    playButton.setTitle(&#34;Play&#34;, for: .normal)
}

// MARK:- AVAudioRecorder delegate methods

func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
    playButton.isEnabled = true
    recordButton.setTitle(&#34;Record&#34;, for: .normal)
}

// MARK:- didReceiveMemoryWarning

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
</code></pre>

<p>}</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p><strong>我发现我的问题出在哪里</strong><br/>
<br/>
看起来,iPhone 模拟器不需要激活 AVAudioSession,而真正的 iPhone 则需要。<br/>
<br/>
因此可以通过添加轻松修复</p>

<pre><code>try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryRecord)
try AVAudioSession.sharedInstance().setActive(true)
</code></pre>

<p>audioRecorder 初始化之前。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - NSUrlRequest 在模拟器中有效,但在 iPhone 上无效,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/45143487/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/45143487/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - NSUrlRequest 在模拟器中有效,但在 iPhone 上无效