Cannot invoke function with an argument list of type '()' - ios

I'm new to IOS development. The constructor of AVAudioRecorder is AVAudioRecorder(URL: filePath, settings: nil, error: nil) in the resource that I'm following but I'm coding in Swift 2 which has different constructor.
The error Cannot invoke function with an argument list of type '()' occurs on "try audioRecorder = AVAudioRecorder(URL: filePath, settings: nil)" line
This is my record audio file :
#IBAction func recordAudio(sender: UIButton) {
stopButton.hidden = false
recordButton.enabled = false
recordingInProgress.hidden = false
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let currentDateTime = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "ddMMyyyy-HHmmss"
let recordingName = formatter.stringFromDate(currentDateTime)+".wav"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
print(filePath)
var session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch {}
do {
try audioRecorder = AVAudioRecorder(URL: filePath, settings: nil)
} catch {}
audioRecorder.meteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}

The way of initializing AVAudioRecorder using its initializer in Swift 2 is to leave out the parameter of type NSErrorPointer and catch it:
do
{
audioRecorder = try AVAudioRecorder(URL:filePath, settings:[:])
}
catch let error as NSError
{
printf(error.description)
}

You are missing error part of the audio recorder initializer:
audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error: nil)

Related

IOS AKAudioRecorder record an audio and save it as Base64String

I'm trying to record an audio and convert it to Base64EncodingString
im using this for init the recorder
private func InitialSetup(){
fileName = NSUUID().uuidString /// unique string value
let audioFilename = getDocumentsDirectory().appendingPathComponent((recordingName?.appending(".m4a") ?? fileName!.appending(".m4a")))
myRecordings.append(recordingName ?? fileName!)
if !checkRepeat(name: recordingName ?? fileName!) { print("Same name reused, recording will be overwritten")}
do{ /// Setup audio player
try audioSession.setCategory(AVAudioSession.Category.playAndRecord, options: .defaultToSpeaker)
audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
audioRecorder.delegate = self
audioRecorder.isMeteringEnabled = true
audioRecorder.prepareToRecord()
audioPlayer.stop()
} catch let audioError as NSError {
print ("Error setting up: %#", audioError)
}
}
and convert file to base64 using this
let path = getDocumentsDirectory().appendingPathComponent(fileName)
let data = try? Data(contentsOf: path)
let base64 = data?.base64EncodedString()
print(base64)
but fail to play the output!
have anybody anyone an idea about this or face this issue before to help me ?

how to save audio file in file manager in ios using swift & also how can i get it?

I use this code to record the audio.
func record() -> Bool {
var settings: [String: Any] = [String: String]()
settings[AVFormatIDKey] = kAudioFormatLinearPCM
settings[AVSampleRateKey] = 8000.0
settings[AVNumberOfChannelsKey] = 1
settings[AVLinearPCMBitDepthKey] = 16
settings[AVLinearPCMIsBigEndianKey] = false
settings[AVLinearPCMIsFloatKey] = false
// settings[AVAudioQuality] = AVEncoderAudioQualityKey
let searchPaths: [String] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true)
let documentPath_ = searchPaths.first
let pathToSave = "\(String(describing: documentPath_))/\(dateString)"
let url = URL.init(fileURLWithPath: pathToSave)
audioRecorder = try? AVAudioRecorder(url: url, settings: settings)
// Initialize degate, metering, etc.
audioRecorder.delegate = self;
audioRecorder.isMeteringEnabled = true;
audioRecorder?.prepareToRecord()
if let recordIs = audioRecorder {
return recordIs.record()
}
return false
}
And then I use this code to get file from file manager & play it but every time arrayListOfRecordSound is blank.**
func play() {
let searchPaths: [String] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .allDomainsMask, true)
let documentPath_ = searchPaths.first
let fileManager = FileManager.default
let arrayListOfRecordSound: [String ]
//if fileManager.fileExists(atPath: getDocumentsDirectory()){
arrayListOfRecordSound = try! fileManager.contentsOfDirectory(atPath: documentPath_!)
// }
print(searchPaths)
print(documentPath_ as Any)
print(arrayListOfRecordSound)
let selectedSound="\(String(describing: documentPath_))/\(String(describing: arrayListOfRecordSound.first))"
let url = URL.init(fileURLWithPath: selectedSound)
let player=try? AVAudioPlayer(contentsOf: url)
player?.delegate = self
try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord,
mode: AVAudioSession.Mode.default,
options: AVAudioSession.CategoryOptions.defaultToSpeaker)
player?.prepareToPlay()
player?.play()
}

record user voice and clear text file every 2 minutes

I am new to swift and I'm working in project that record user sound ,and convert sound file into text file every two minutes. I use timer to repeat the step every 2 minutes.
the problem is that the recorder is disable for the second call. Also, the text file does not clear the content to be prepared to the next call.
here is the full code.
import UIKit
import Speech
import AVFoundation
class ViewController: UIViewController {
var audioRecorder:AVAudioRecorder!
var inString = ""
let fileName = "Test"
var str=""
appropriateFor: nil, create: true)
let recordSettings = [AVSampleRateKey : NSNumber(value: Float(44100.0)),
AVFormatIDKey : NSNumber(value: Int32(kAudioFormatMPEG4AAC)),
AVNumberOfChannelsKey : NSNumber(value: Int32(1)),
AVEncoderAudioQualityKey : NSNumber(value: Int32(AVAudioQuality.high.rawValue))]
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioRecorder = AVAudioRecorder(url: directoryURL()!, settings: recordSettings)
audioRecorder.prepareToRecord()
} catch {
print("error")
}
audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
requestSpeechAuth()
} catch {}
timer = Timer.scheduledTimer(timeInterval: 120, target: self, selector: #selector (ViewController.stopAudio), userInfo: nil, repeats: true)
}
#objc func stopAudio() {
audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(false)
let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "ar_SA"))
let request = SFSpeechURLRecognitionRequest(url: audioRecorder.url)
recognizer?.recognitionTask(with: request) { (result, error) in
if let error = error {
print("There was an error: \(error)")
} else {
let dir = try? FileManager.default.url(for: .documentDirectory,
in: .userDomainMask, appropriateFor: nil, create: true)
if let fileURL = dir?.appendingPathComponent(self.fileName).appendingPathExtension("txt") {
do {
self.str=""
self.str = (result?.bestTranscription.formattedString)!
try self.str.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
do {
self.inString = try String(contentsOf: fileURL)
} catch {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
self.getIqama(fileN: self.inString,status: self.str)
}
}//end elsd
} //end result
} catch {} //end do for false
// requestSpeechAuth()
}
func directoryURL() -> URL? {
let fileManager = FileManager.default
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = urls[0] as URL
let soundURL = documentDirectory.appendingPathComponent("AqimAlsalat.m4a")
return soundURL
}
func getIqama(fileN : String, status:String)
{
var st: String!
st = "السلام عليكم ورحمة الله السلام عليكم ورحمة الله"
let st1 : String!
st1 = String (fileN)
print(st1)
if st1 == st {
// audioEngine.stop()
//speechRecognitionRequest?.endAudio()
print(st1)
print("JJalal")
}
else {
print("Dalal")
print(fileN)
}
}
func requestSpeechAuth(){
SFSpeechRecognizer.requestAuthorization { authStatus in
if authStatus == SFSpeechRecognizerAuthorizationStatus.authorized {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(true)
self.audioRecorder.record()
} catch {}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
any suggestion or idea?
Thanks
It seems like you need to call self.audioRecorder.record() again after you stop the recording to convert the soundfile into text. The Apple docs say that calling record() will create or erase an audio file, so that should solve your problem.
However, you may encounter another problem where you miss a period of recording while you are transcribing the text. You could consider fixing that problem by switching back and forth between two recorders, or you could try to change the audio recorder's file location (or change the location of the previous file) before starting to record again.

Xcode 8.0 beta3 AVAudioRecorder(url,setting) error catch - "Error Domain=NSOSStatusErrorDomain Code=-50 "(null)""

I'm trying to record the voice of the user and change it to a text data. I used AVAudioRecorder to record the sound and SpeechKit to change it to text which is included in iOS 10. When user touches down the button record starts and stops when button is touched up. But when I initialize the AVAudioRecorder using do catch syntax, error occurs and fails.
I added the appropriate frameworks(Speech, AVFoundation).
import UIKit
import Speech
import AVFoundation
class SearchViewController: UIViewController, CLLocationManagerDelegate, AVAudioRecorderDelegate {
var audioRecorder = AVAudioRecorder()
let recordSettings = [AVSampleRateKey : String(NSNumber(value: Float(44100.0))),
AVFormatIDKey : String(kAudioFileCAFType),
AVNumberOfChannelsKey : String(NSNumber(value: 2))]
#IBAction func recordButtonDown(_ sender: AnyObject) {
print("recordButtonDown")
self.audioPlayer.play()
sleep(1)
let fileManager = FileManager.default
let paths = fileManager.urlsForDirectory(.documentDirectory, inDomains: .userDomainMask)
var audioURL = paths[0] as NSURL
audioURL = audioURL.appendingPathComponent("soundForMapSearch.caf", isDirectory: false)!
do {
self.audioRecorder = try AVAudioRecorder(url: soundFileURL as URL, settings: self.recordSettings)
self.audioRecorder.delegate = self
self.audioRecorder.prepareToRecord()
self.audioRecorder.record()
} catch (let error) {
print("Error: \(error)")
}
}
#IBAction func recordButtonUp(_ sender: AnyObject) {
self.audioRecorder.stop()
}
override func viewDidLoad() {
super.viewDidLoad()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioSession.setActive(true)
audioSession.requestRecordPermission({ (recordPermission) in
})
} catch {
print("record initiallizing failed")
}
And on the line
self.audioRecorder = try AVAudioRecorder(url: soundFileURL as URL, settings: self.recordSettings)
error occurs at catch
Error: Error Domain=NSOSStatusErrorDomain Code=-50 "(null)"
is printed. I searched for this error and code=-50 means the NSURL object is invalid. How can I solve this error?
my working code
let recordingName = "recording1" + ".m4a"
let pathArray = [dirPath, recordingName]
print(pathArray)
let filePath = NSURL.fileURL(withPathComponents: pathArray)
print(filePath)
do{
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch {
assertionFailure("AVAudioSession setup error: \(error)")
}
let recordSettings: [String: AnyObject] = [
AVFormatIDKey: NSNumber(value: kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100.0,
AVNumberOfChannelsKey: 1,
]
try! audioRecorder = AVAudioRecorder(url: filePath!, settings: recordSettings)
audioRecorder.delegate = self
audioRecorder.isMeteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()

Using AVAudioRecorder to record voice

I'm trying to make a simple voice recorder. I'm using Xcode-beta 7 and I've based my code off of these three sources.
AVFoundation Audio Recording With Swift
AVAudioRecorder Reference to see the inputs of the initializers.
Recording audio in Swift to get the Settings that I should use
I'm using the following code:
var recordSettings = [
AVFormatIDKey: kAudioFormatAppleIMA4,
AVLinearPCMIsBigEndianKey: 0,
AVLinearPCMIsFloatKey: 0,
AVNumberOfChannelsKey: 2,
AVSampleRateKey: 32000
]
var session = AVAudioSession.sharedInstance()
do{
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
recorder = AVAudioRecorder(URL: filePath, settings: recordSettings, error: nil)
}catch{
print("Error")
}
but it says that "Cannot find an initializer for type 'AVAudioRecorder' that accepts an argument list of type '(URL:NSURL?, settings:[String:AudioFormatID], error:nil)'"
Aren't my inputs exactly what the documentation asks for?
AVAudioRecorder does not need anymore the error parameter:
init(URL url: NSURL, settings settings: [String : AnyObject]) throws
Also, I needed to unwrap the filePath, as suggested in a previous answer:
func recordSound(){
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let recordingName = "my_audio.wav"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue,
AVEncoderBitRateKey: 16,
AVNumberOfChannelsKey: 2,
AVSampleRateKey: 44100.0]
print(filePath)
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
audioRecorder = try AVAudioRecorder(URL: filePath!, settings: recordSettings as! [String : AnyObject])
} catch _ {
print("Error")
}
audioRecorder.delegate = self
audioRecorder.meteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
Your filePath is wrapped as an optionnal. You should check if isn't nil and unwrap it like this:
recorder = AVAudioRecorder(URL: filePath!, settings: recordSettings, error: nil)
And you need to pass an NSError pointer too:
var error: NSError?
recorder = AVAudioRecorder(URL: filePath!, settings: recordSettings, error: &error)
After that, if you have error in your settings dictionnay, try to transform all Tnt to NSNumber, because NSNumber is an Object, not Int. Example:
NSNumber(integer: kAudioFormatAppleIMA4)

Resources