Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Samplem4a
//
// ViewController.swift
// Samplem4a
//
// Created by 永田大祐 on 2021/03/28.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
private var btPlay = UIButton()
private var btRecord = UIButton()
private var player = AudioEnginePlayer()
override func viewDidLoad() {
super.viewDidLoad()
btPlay.frame = CGRect(x: 0,
y: view.frame.height - 200,
width: self.view.frame.width,
height: 100)
btPlay.addTarget(self, action: #selector(playBack), for: .touchUpInside)
btPlay.setTitle("Play", for: .normal)
btPlay.setTitleColor(.black, for: .normal)
view.addSubview(btPlay)
btRecord.frame = CGRect(x: 0,
y: view.frame.height - 100,
width: self.view.frame.width,
height: 100)
btRecord.addTarget(self, action: #selector(record), for: .touchUpInside)
btRecord.setTitle("Record", for: .normal)
btRecord.setTitleColor(.black, for: .normal)
view.addSubview(btRecord)
}
@objc func playBack() {
player.stop()
player.play()
}
@objc func record() {
player.stop()
player.record()
}
}
class AudioEnginePlayer {
var audioPlayerNode: AVAudioPlayerNode = AVAudioPlayerNode()
var audioEngine: AVAudioEngine = AVAudioEngine()
private var audioFile: AVAudioFile?
private var session = AVAudioSession.sharedInstance()
init() {
setFile(url: getAudioFileUrl())
}
func play() {
guard !audioEngine.isRunning, audioFile == nil else { return }
do {
let audioFile = try AVAudioFile(forReading: getAudioFileUrl())
audioPlayerNode.scheduleFile(audioFile, at: nil, completionHandler: nil)
try audioEngine.start()
audioPlayerNode.play()
} catch let error {
print(error)
}
}
func record() {
setFile(url: getAudioFileUrl())
audioEngine.inputNode.installTap(onBus: 0, bufferSize: 1024, format: audioEngine.inputNode.outputFormat(forBus: 0)) { [self] (buffer, time) in
do {
try audioFile?.write(from: buffer)
} catch let error {
print(error, "error")
}
}
setUrl()
}
// audioFile = nilをしないとファイルが動作しない
func stop() {
audioPlayerNode.stop()
audioEngine.stop()
audioEngine.inputNode.removeTap(onBus: 0)
audioFile = nil
}
func getAudioFileUrl() -> URL {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
return documentsDirectory.appendingPathComponent("sample.m4a")
}
private func setUrl() {
// Prepare AVAudioPlayerNode
audioEngine.attach(audioPlayerNode)
audioEngine.connect(audioPlayerNode, to: audioEngine.mainMixerNode, format: audioFile?.processingFormat)
do {
audioEngine.prepare()
try audioEngine.start()
} catch let error {
print(error)
}
}
private func setFile(url: URL) {
do {
let format = AVAudioFormat(commonFormat: .pcmFormatInt32 , sampleRate: AVAudioSession.sharedInstance().sampleRate, channels: 1 , interleaved: false)
audioFile = try AVAudioFile(forWriting:url, settings: format!.settings)
sessionEngine()
} catch let error {
print(error)
}
}
private func sessionEngine() {
do {
try session.setCategory(.playAndRecord, mode: .default, options: .defaultToSpeaker)
try session.overrideOutputAudioPort(.speaker)
try session.setPreferredSampleRate(AVAudioSession.sharedInstance().sampleRate)
try session.setActive(true)
} catch let error {
print("engine.start() error:", error)
}
}
}
@daisukenagata

This comment has been minimized.

Copy link
Owner Author

@daisukenagata daisukenagata commented Mar 28, 2021

スクリーンショット 2021-03-28 23 41 54

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment