Last active
November 7, 2017 22:56
-
-
Save tad-iizuka/6856d531125468ebd40f91c16ef5f6ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func startRecord() { | |
// 出力ファイルパスを初期化、録音中に設定 | |
self.filePath = nil | |
self.isRec = true | |
// Audio Sessionを再生&録音モードに変更 | |
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord) | |
try! AVAudioSession.sharedInstance().setActive(true) | |
// 再生ファイル(1K.mp3)を読み込み | |
self.audioFile = try! AVAudioFile(forReading: Bundle.main.url(forResource: "1K", withExtension: "mp3")!) | |
// 録音フォーマット(44.1K PCM 16Bit インターリーブ)を設定 | |
let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16, | |
sampleRate: 44100.0, | |
channels: 1, | |
interleaved: true) | |
// Nodeを接続(Mic -> Mixer, Player -> Mixer, Mixer -> MainMixer) | |
// Playerの音声フォーマットはファイルのフォーマットに従う | |
self.audioEngine.connect(self.audioEngine.inputNode!, to: self.mixer, format: format) | |
self.audioEngine.connect(self.audioFilePlayer, to: self.mixer, format: self.audioFile.processingFormat) | |
self.audioEngine.connect(self.mixer, to: self.audioEngine.mainMixerNode, format: format) | |
// Playerの再生場所(先頭)を指定(途中再生の場合、再生する Frame Positionを Starting Frameに設定する) | |
self.audioFilePlayer.scheduleSegment(audioFile, | |
startingFrame: AVAudioFramePosition(0), | |
frameCount: AVAudioFrameCount(self.audioFile.length), | |
at: nil, | |
completionHandler: self.completion) | |
// 出力ファイルのパスを生成 | |
let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String | |
self.filePath = dir.appending("/temp.wav") | |
// 書込みファイル(.wav)を生成(&outref) | |
_ = ExtAudioFileCreateWithURL(URL(fileURLWithPath: self.filePath!) as CFURL, | |
kAudioFileWAVEType, | |
format.streamDescription, | |
nil, | |
AudioFileFlags.eraseFile.rawValue, | |
&outref) | |
// mixerの Tapする(BufferSize毎に Callback(Void in)が呼ばれる) | |
self.mixer.installTap(onBus: 0, bufferSize: AVAudioFrameCount(format.sampleRate * 0.4), format: format, block: { (buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in | |
// 音声データの書き込み | |
let audioBuffer : AVAudioBuffer = buffer | |
_ = ExtAudioFileWrite(self.outref!, buffer.frameLength, audioBuffer.audioBufferList) | |
}) | |
// 再生&録音の開始 | |
try! self.audioEngine.start() | |
self.audioFilePlayer.play() | |
} | |
func stopRecord() { | |
// 録音停止 | |
self.isRec = false | |
self.audioFilePlayer.stop() | |
self.audioEngine.stop() | |
// Tapを削除(登録したままにすると次に Installした時点でエラーになる) | |
self.mixer.removeTap(onBus: 0) | |
// ファイル書き込み | |
ExtAudioFileDispose(self.outref!) | |
// Audio sessionを停止 | |
try! AVAudioSession.sharedInstance().setActive(false) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment