Record and play audio Simultaneously

时光总嘲笑我的痴心妄想 提交于 2019-11-26 07:38:17

问题


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


回答1:


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.

See Apple's aurioTouch sample app for example code.




回答2:


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.




回答3:


Please Check aurioTouch apple sample code for audio record-and-play simultaneously

You can also check Recording Audio on an iPhone




回答4:


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!

https://github.com/casspangell/AudioMic




回答5:


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.

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.



来源:https://stackoverflow.com/questions/4215180/record-and-play-audio-simultaneously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!