ios 同时录制和播放音频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4215180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:06:53  来源:igfitidea点击:

Record and play audio Simultaneously

iosobjective-ccore-audioaudio-recording

提问by arunkumar.p

Any one help to me to record and play audio Simultaneously in Iphone.

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

回答by hotpaw2

You can play and record simultaneously on iOS devices (except the 1st gen Touch) using either the Audio Unit RemoteIO or the Audio Queue API. These are lower level APIs where you have to handle the incoming buffers of outgoing and incoming PCM samples yourself.

您可以使用 Audio Unit RemoteIO 或 Audio Queue API 在 iOS 设备(第一代 Touch 除外)上同时播放和录音。这些是较低级别的 API,您必须自己处理传入和传出 PCM 样本的传入缓冲区。

See Apple's aurioTouch sample app for example code.

有关示例代码,请参阅 Apple 的 aurioTouch 示例应用程序。

回答by iPrabu

You can get a use from AVFoundation framework. It has AVAudioPlayer to play audio files and AVAudioRecorder to record. You have to bear in mind that Recorder will record with the use of mic only. So with the simultameously playing a audio file and recording it depends on how the mic will perceive the audio that is played.

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

回答by Saif

Please Check aurioTouchapple sample code for audio record-and-play simultaneously

请检查aurioTouch苹果示例代码以同时进行音频录制和播放

You can also check Recording Audio on an iPhone

您还可以检查在 iPhone 上录制音频

回答by mondousage

Hope this helps some folks... I made an app that records audio, say from an app like Pandora and can playback the audio. Run/Play an audio app, run AudioMic, record, turn the audio app sound off, go back and play the recorded audio from AudioMic. Yay!

希望这可以帮助一些人......我制作了一个记录音频的应用程序,比如来自 Pandora 之类的应用程序,并且可以播放音频。运行/播放音频应用程序,运行 AudioMic,录制,关闭音频应用程序声音,返回并从 AudioMic 播放录制的音频。好极了!

https://github.com/casspangell/AudioMic

https://github.com/casspangell/AudioMic

回答by Himanshu Mahajan

To record an play the audio files in iOS, you can use AVFoundation framework. Use below swift code to record and play the audios. Remember that recorder will record the audio with the use of mic, so please test this code on device.

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

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
}
}

I had tested this code on xCode 7.0 & iOS 9.

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