AVAudioEngineで保存したファイル。1回目が再生できない
AVAudioEnginを使って音声をファイルに保存と再生するプログラムを作ってみましたが、1回目が再生できません。2回目からは録音-再生はできるようになりました。
どうしてなのかwebを漁ってみましたがどうにもわかりません。
Frameworkもswiftも基本的な理解ができてなく。そんな状況で質問とは心苦しいのですが、どうすれば1回目から再生できるかアドバイスをよろしくお願いします。
import UIKit
import AVFoundation
class ViewController: UIViewController,AVAudioPlayerDelegate {
var recBtn: UIButton!
var playBtn: UIButton!
var file: AVAudioFile?
var player = AVAudioPlayerNode()
var path: String!
var engine:AVAudioEngine!
var mixer:AVAudioMixerNode!
var input:AVAudioInputNode!
var audioFile:AVAudioFile!
var audioRecorder:AVAudioRecorder!
var audioPlayer:AVAudioPlayer!
var filePath:NSURL!
let settings = [
AVFormatIDKey: kAudioFormatLinearPCM,
AVSampleRateKey: 44100.0,
AVNumberOfChannelsKey: 1 ]
override func viewDidLoad() {
super.viewDidLoad()
recBtn = UIButton(frame: CGRectMake( 0, 0, 100, 40))
recBtn.setTitle("RECORD", forState: UIControlState.Normal)
recBtn.setTitleColor(UIColor.blackColor(), forState:.Normal)
recBtn.center = CGPointMake(self.view.bounds.width/2, 200)
recBtn.backgroundColor=UIColor.lightGrayColor()
self.view.addSubview(recBtn)
playBtn = UIButton(frame: CGRectMake( 0, 0, 100, 40))
playBtn.setTitle("PLAY", forState: UIControlState.Normal)
playBtn.setTitleColor(UIColor.blackColor(), forState:.Normal)
playBtn.center = CGPointMake(self.view.bounds.width/2, 300)
playBtn.backgroundColor=UIColor.lightGrayColor()
self.view.addSubview(playBtn)
recBtn.addTarget(self, action: "recbtn", forControlEvents:UIControlEvents.TouchDown)
recBtn.addTarget(self, action: "recbtnRelease", forControlEvents:UIControlEvents.TouchUpInside)
playBtn.addTarget(self, action: "pplay", forControlEvents:UIControlEvents.TouchDown)
playBtn.addTarget(self, action: "play", forControlEvents:UIControlEvents.TouchUpInside)
initEngine()
}
func initEngine(){
filePath = URLFor("testrecord.wav")
engine = AVAudioEngine()
input = engine.inputNode
mixer = engine.mainMixerNode
mixer.outputVolume = 1.0
}
func URLFor(filename: String) -> NSURL? {
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
let dir = dirs[0]
path = dir.stringByAppendingPathComponent(filename)
println(path)
return NSURL(fileURLWithPath: path)
}
return nil
}
func recbtn() {
recBtn.backgroundColor=UIColor.redColor()
var iformat = engine.inputNode.inputFormatForBus(0)
engine.connect(input, to: mixer, format: iformat)
engine.startAndReturnError(nil)
audioFile = AVAudioFile(forWriting: filePath, settings: settings as [NSObject : AnyObject], error: nil)
let Input = engine.inputNode
Input.installTapOnBus(0, bufferSize: 4096, format: audioFile.processingFormat) {
(buffer : AVAudioPCMBuffer!, when : AVAudioTime!) in
self.audioFile.writeFromBuffer(buffer, error: nil)
}
}
func recbtnRelease() {
recBtn.backgroundColor=UIColor.lightGrayColor()
var error: NSError?
println("recbuttonReleaqse")
engine.stop()
engine.inputNode.removeTapOnBus(0)
if let attr: NSDictionary = NSFileManager.defaultManager().attributesOfItemAtPath(path!, error: &error) {
println(attr.fileModificationDate())
println(attr.fileSize())
}else{
println("DAME")
}
}
func pplay(){
playBtn.backgroundColor=UIColor.redColor()
}
func play() {
playBtn.backgroundColor=UIColor.lightGrayColor()
var attr: NSDictionary
var error: NSError?
if let attr: NSDictionary = NSFileManager.defaultManager().attributesOfItemAtPath(path!, error: &error) {
println(attr.fileModificationDate())
println(attr.fileSize())
}else{
println("error \(error!.localizedDescription)")
}
audioPlayer = AVAudioPlayer(contentsOfURL:filePath,error: nil)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}