【问题标题】:Record and play audio Simultaneously同时录制和播放音频
【发布时间】:2011-05-12 00:57:06
【问题描述】:

任何人都可以帮助我在 Iphone 中同时录制和播放音频。

【问题讨论】:

  • 向我发送更多描述。录音应该用麦克风吗?同步的精确度等。也许您应该查看苹果示例代码 aurioTouch。
  • 您可以使用 Audio Unit RemoteIO 或 Audio Queue API 在 iOS 设备(第一代 Touch 除外)上同时播放和录制。这些是较低级别的 API,您必须自己处理传出和传入 PCM 样本的传入缓冲区。有关示例代码,请参阅 Apple 的 aurioTouch 示例应用程序。

标签: ios objective-c core-audio audio-recording


【解决方案1】:

您可以从 AVFoundation 框架中获得使用。它有 AVAudioPlayer 播放音频文件和 AVAudioRecorder 录制。 您必须记住,录音机将仅使用麦克风进行录音。 因此,同时播放音频文件和录音取决于麦克风如何感知播放的音频。

【讨论】:

    【解决方案2】:

    请查看aurioTouch苹果同时录音和播放示例代码

    您也可以查看Recording Audio on an iPhone

    【讨论】:

      【解决方案3】:

      要在 iOS 中录制播放音频文件,您可以使用 AVFoundation 框架。使用下面的快速代码来录制和播放音频。 请记住,录音机将使用麦克风录制音频,因此请在设备上测试此代码。

      import UIKit
      import AVFoundation
      
      extension String {
      
             func stringByAppendingPathComponent(path: String) -> String {
      
             let nsSt = self as NSString
             return nsSt.stringByAppendingPathComponent(path)
          }
      }
      
      class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate{
      
      var audioPlayer : AVAudioPlayer!
      var audioRecorder : AVAudioRecorder!
      
      @IBOutlet var recordButton : UIButton!
      @IBOutlet var playButton : UIButton!
      @IBOutlet var stopButton : UIButton!
      
      override func viewDidLoad() {
          super.viewDidLoad()
      
          self.recordButton.enabled = true
          self.playButton.enabled = false
          self.stopButton.enabled = false
      }
      
      override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning()
      }
      
      //MARK: UIButton action methods
      
      @IBAction func playButtonClicked(sender : AnyObject){
      
          let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
          dispatch_async(dispatchQueue, {
      
              if let data = NSData(contentsOfFile: self.audioFilePath())
              {
                  do{
                      self.audioPlayer = try AVAudioPlayer(data: data)
                      self.audioPlayer.delegate = self
                      self.audioPlayer.prepareToPlay()
                      self.audioPlayer.play()
                  }
                  catch{
                      print("\(error)")
                  }
              }
          });
      }
      
      @IBAction func stopButtonClicked(sender : AnyObject){
      
          if let player = self.audioPlayer{
              player.stop()
          }
      
          if let record = self.audioRecorder{
      
              record.stop()
      
              let session = AVAudioSession.sharedInstance()
              do{
                  try session.setActive(false)
              }
              catch{
                  print("\(error)")
              }
          }
      }
      
      @IBAction func recordButtonClicked(sender : AnyObject){
      
          let session = AVAudioSession.sharedInstance()
      
          do{
              try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
              try session.setActive(true)
              session.requestRecordPermission({ (allowed : Bool) -> Void in
      
                  if allowed {
                      self.startRecording()
                  }
                  else{
                      print("We don't have request permission for recording.")
                  }
              })
          }
          catch{
              print("\(error)")
          }
      }
      
      func startRecording(){
      
          self.playButton.enabled = false
          self.recordButton.enabled = false
          self.stopButton.enabled = true
      
          do{
      
              let fileURL = NSURL(string: self.audioFilePath())!
              self.audioRecorder = try AVAudioRecorder(URL: fileURL, settings: self.audioRecorderSettings() as! [String : AnyObject])
      
              if let recorder = self.audioRecorder{
                  recorder.delegate = self
      
                  if recorder.record() && recorder.prepareToRecord(){
                      print("Audio recording started successfully")
                  }
              }
          }
          catch{
              print("\(error)")
          }
      }
      
      func audioFilePath() -> String{
      
          let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
          let filePath = path.stringByAppendingPathComponent("test.caf") as String
      
          return filePath
      }
      
      func audioRecorderSettings() -> NSDictionary{
      
          let settings = [AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)), AVSampleRateKey : NSNumber(float: Float(16000.0)), AVNumberOfChannelsKey : NSNumber(int: 1), AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Medium.rawValue))]
      
          return settings
      }
      
      //MARK: AVAudioPlayerDelegate methods
      
      func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
      
          if flag == true{
              print("Player stops playing successfully")
          }
          else{
              print("Player interrupted")
          }
      
          self.recordButton.enabled = true
          self.playButton.enabled = false
          self.stopButton.enabled = false
      }
      
      //MARK: AVAudioRecorderDelegate methods
      
      func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
      
          if flag == true{
              print("Recording stops successfully")
          }
          else{
              print("Stopping recording failed")
          }
      
          self.playButton.enabled = true
          self.recordButton.enabled = false
          self.stopButton.enabled = false
      }
      }
      

      我在 xCode 7.0 和 iOS 9 上测试过这段代码。

      【讨论】:

      • 我要录制输出音频(我的意思是直播音频或扬声器音频)
      • in iOS 12.4.1 当音频在后台播放时(所以当应用程序不在前台时),此解决方案不会开始录制
      猜你喜欢
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      相关资源
      最近更新 更多