AVAudioPlayer working on Simulator but not on Real Device - ios

While I play recorded Audio I get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
on this line of code:
SoundPlayer = try AVAudioPlayer(contentsOfURL: getFileURL())
But it is working perfectly on Simulator except real device.
ViewController.Swift:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate {
#IBOutlet var PlayBTN: UIButton!
#IBOutlet var RecordBTN: UIButton!
var soundRecorder : AVAudioRecorder!
var SoundPlayer : AVAudioPlayer!
var fileName = "audioFile.m4a"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupRecorder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupRecorder(){
let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),
AVNumberOfChannelsKey : NSNumber(int: 1),
AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Max.rawValue))]
do{
try soundRecorder = AVAudioRecorder(URL: getFileURL(), settings: recordSettings)
soundRecorder.delegate = self
soundRecorder.prepareToRecord()
}
catch let error as NSError {
error.description
}
}
func getCacheDirectory() -> String {
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
return paths[0]
}
func getFileURL() -> NSURL{
let path = (getCacheDirectory() as NSString).stringByAppendingPathComponent(fileName)
let filePath = NSURL(fileURLWithPath: path)
return filePath
}
#IBAction func Record(sender: UIButton) {
if sender.titleLabel?.text == "Record"{
soundRecorder.record()
sender.setTitle("Stop", forState: .Normal)
PlayBTN.enabled = false
}
else{
soundRecorder.stop()
sender.setTitle("Record", forState: .Normal)
PlayBTN.enabled = false
}
}
#IBAction func PlaySound(sender: UIButton) {
if sender.titleLabel?.text == "Play" {
RecordBTN.enabled = false
sender.setTitle("Stop", forState: .Normal)
preparePlayer()
SoundPlayer.play()
}
else{
SoundPlayer.stop()
sender.setTitle("Play", forState: .Normal)
}
}
func preparePlayer(){
do{
SoundPlayer = try AVAudioPlayer(contentsOfURL: getFileURL())
SoundPlayer.delegate = self
SoundPlayer.volume = 1.0
SoundPlayer.prepareToPlay()
}
catch let error as NSError {
error.description
}
}
func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
PlayBTN.enabled = true
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
RecordBTN.enabled = true
PlayBTN.setTitle("Play", forState: .Normal)
}
#IBAction func actDone(sender: AnyObject) {
//viewRecorder.hidden = true
let fm = NSFileManager.defaultManager()
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
do {
let items = try fm.contentsOfDirectoryAtPath(documentsDirectory)
for item in items {
print(item)
}
}
catch let error as NSError {
error.description
}
}
}
Storyboard file for ViewController.Swift:
Additional info:
Xcode version : 7.2.1
Device : iPhone 5s
iOS version : 9.2.1
Note: I have looked for similar SO solutions but none of them helped me. Some of them due to older Swift version and deprecated method. Some solutions were regarding playing audio file from application bundle and some of were using web URLs. So, this case is different(Real Device vs Simulator)
Here is the link of source code on Google Drive.

On a real device, it needs to setCategory() for AVAudioSession.sharedInstance()
And a fixed project can be downloaded here too.
func setupRecorder(){
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch let error as NSError {
print(error.description)
}
let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),
AVNumberOfChannelsKey : NSNumber(int: 1),
AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Max.rawValue))]
do{
try soundRecorder = AVAudioRecorder(URL: getFileURL(), settings: recordSettings)
soundRecorder.delegate = self
soundRecorder.prepareToRecord()
}
catch let error as NSError {
error.description
}
}
NOTE: An audio session is the intermediary between your app and iOS used to configure your app’s audio behaviour. If we set category for AVAudioSessionCategoryPlayAndRecord, we define iOS audio behaviour to allow audio input (recording) and output (playback).
Referred from: Audio Session Programming Guide

Related

iOS - converting to fmp4 (from mp4/m4a) and streaming it

So I didn't managed to find any code about this issue.
I have recorded an mp4 file(audioFile.mp4) and now i want to stream it through socket , yet i have problem in converting.
I know that there is the ffmpeg(https://www.ffmpeg.org/) platform yet i didn't see any code of that.
Would appreciate any idea.
class ViewController: UIViewController {
var requestManager = RequestManager()
var socket: WebSocket?
var audioRecorder: AVAudioRecorder!
#IBOutlet weak var recordBtn: UIButton!
#IBOutlet weak var playBtn: UIButton!
var fileName: String = "audioFile.mp4"
var soundRecorder: AVAudioRecorder?
var soundPlayer: AVAudioPlayer?
var audioSession = AVAudioSession.sharedInstance()
override func viewDidLoad() {
super.viewDidLoad()
self.socket?.delegate = self
setUpRecorder()
playBtn.isEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSession.Category.playAndRecord, mode: .measurement, options: .defaultToSpeaker)
try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
} catch {
print(error)
}
}
func getDocDirector() -> URL {
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return path[0]
}
func setUpRecorder() {
let audioFileName = getDocDirector().appendingPathComponent(fileName)
let recordSettings: [String: Any] = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
AVNumberOfChannelsKey: 1,
AVEncoderBitRateKey: 16000,
AVSampleRateKey: 16000]
do {
soundRecorder = try AVAudioRecorder(url: audioFileName, settings: recordSettings)
soundRecorder?.delegate = self
soundRecorder?.prepareToRecord()
} catch {
print(error)
}
}
func setUpPlayer() {
let audioFileName = getDocDirector().appendingPathComponent(fileName)
do {
soundPlayer = try AVAudioPlayer(contentsOf: audioFileName)
soundPlayer?.delegate = self
soundPlayer?.prepareToPlay()
soundPlayer?.volume = 1.0
} catch {
print(error)
}
}
#IBAction func recordAction(_ sender: Any) {
if recordBtn.titleLabel?.text == "Record" {
soundRecorder?.record()
recordBtn.setTitle("Stop", for: .normal)
playBtn.isEnabled = false
} else {
soundRecorder?.stop()
recordBtn.setTitle("Record", for: .normal)
playBtn.isEnabled = false
}
}
#IBAction func playAction(_ sender: Any) {
if playBtn.titleLabel?.text == "Play" {
playBtn.setTitle("Stop", for: .normal)
recordBtn.isEnabled = false
setUpPlayer()
soundPlayer?.play()
} else {
playBtn.setTitle("Play", for: .normal)
recordBtn.isEnabled = false
}
}
func openSocket() {
getUrl(success: { [weak self] (url) in
self?.socket = WebSocket(url: URL(string: url)!)
self?.socket?.connect()
}) { (e) in
//
}
}
}

Automatically Start audio recording when user speaks

I am trying to start recording when the user starts to talk and stops recording when the user is done talking. And I want to limit the maximum record audio length.I could not be able to find enough function in AVAudioRecorderDelegate.Hope you understand my problem.Thanks in Advance
#IBAction func recordAudio(_ sender: Any) {
recordingLabel.text = "Recording in progress..."
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0] as String
let recordingName = "recordedVoice.wav"
let pathArray = [dirPath, recordingName]
let filePath = URL(string: pathArray.joined(separator: "/"))
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, with:AVAudioSessionCategoryOptions.defaultToSpeaker)
try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
audioRecorder.delegate = self
audioRecorder.isMeteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
#IBAction func stopRecording(_ sender: Any) {
recordButton.isEnabled = true
stopRecordingButton.isEnabled = false
recordingLabel.text = "Tap to record..."
audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setActive(false)
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if (flag) {
//Success
} else {
print("Could not save audio recording!")
}
}
To Record Audio When user tak1 you need some steps
1. Permission from User to all your app to use Mic
In your Info Plist Add Privacy - Microphone Usage Description in user Plist and add Text Description
2. Location to save Recorded File user FileManager
3. To End After time : use audioRecorder.record(forDuration: 30) // record for 30 Sec
Check complete code :
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var recordButton: UIButton!
var recordingSession: AVAudioSession!
var audioRecorder: AVAudioRecorder!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func recordAudio(_ sender: Any) {
self.requestRecordPermission()
}
func requestRecordPermission() {
recordingSession = AVAudioSession.sharedInstance()
do {
try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try recordingSession.setActive(true)
recordingSession.requestRecordPermission() { [unowned self] allowed in
DispatchQueue.main.async {
if allowed {
// User allow you to record
// Start recording and change UIbutton color
self.recordButton.backgroundColor = .red
self.startRecording()
} else {
// failed to record!
}
}
}
} catch {
// failed to record!
}
}
func startRecording() {
let audioFilename = getDocumentsDirectory().appendingPathComponent("recordedFile.m4a")
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
audioRecorder.delegate = self
audioRecorder.record(forDuration: 30) // record for 30 Sec
recordButton.setTitle("Tap to Stop", for: .normal)
recordButton.backgroundColor = .green
} catch {
finishRecording(success: false)
}
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
#objc func recordTapped() {
if audioRecorder == nil {
startRecording()
} else {
finishRecording(success: true)
}
}
public func finishRecording(success: Bool) {
audioRecorder.stop()
audioRecorder = nil
if success {
// record sucess
recordButton.backgroundColor = .green
} else {
// record fail
recordButton.backgroundColor = .yellow
}
}
}
extension ViewController :AVAudioRecorderDelegate{
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
if !flag {
finishRecording(success: false)
}
}
}

AVAudioPlayer playing recorded audio in simulator but not on phone

I'm trying to create an app that simply records and plays audio. I have tried multiple different methods of playing audio but it does not seem to work when playing on an iPhone 6 and an iPhone 8 Plus but works on the simulator.
The error:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
This happens when SoundPlayer is trying to play. The error printed in the console is:
Error Domain=NSOSStatusErrorDomain Code=2003334207 "(null)"
#IBOutlet weak var recordBtn: UIButton!
#IBOutlet weak var playBtn: UIButton!
var soundRecorder : AVAudioRecorder!
var soundPlayer : AVAudioPlayer!
var fileName = "audioFile0.aac"
var screenCounter = 0 (global variable)
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override open func viewDidLoad() {
super.viewDidLoad()
if (screenCounter == 0){
// Do any additional setup after loading the view, typically from a nib.
setupRecorder()
screenCounter += 1
}
}
func setupRecorder(){
let recordSettings = [ AVFormatIDKey : kAudioFormatMPEG4AAC
, AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue, AVEncoderBitRateKey : 320000, AVNumberOfChannelsKey : 2, AVSampleRateKey : 44100.0 ] as [String : Any]
let _ : NSError?
do{
soundRecorder = try AVAudioRecorder(url : getFileURL() as URL, settings : recordSettings)
}catch{
print("Something went wrong")
}
soundRecorder.delegate = self
soundRecorder.prepareToRecord()
}
func getCacheDirectory() -> String{
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
return paths[0]
}
func getFileURL() -> NSURL{
let pathURL = NSURL(fileURLWithPath : getCacheDirectory()).appendingPathComponent(fileName)
let pathString = pathURL?.path
let filePath = NSURL(fileURLWithPath : pathString!)
return filePath
}
#IBAction func record(_ sender: UIButton) {
if sender.titleLabel?.text == "Record"{
soundRecorder.record()
sender.setTitle("Stop", for : .normal)
playBtn.isEnabled = false
}else{
soundRecorder.stop()
sender.setTitle("Record", for : .normal)
playBtn.isEnabled = false
}
}
#IBAction func playSound(_ sender: UIButton) {
if sender.titleLabel?.text == "Play"{
recordBtn.isEnabled = false
sender.setTitle("Stop", for : .normal)
preparePlayer()
soundPlayer.play()
}else{
soundPlayer.stop()
sender.setTitle("Play", for : .normal)
}
}
func preparePlayer(){
let _ : NSError?
do{
soundPlayer = try AVAudioPlayer(contentsOf : getFileURL() as URL)
}catch{
print(error)
}
soundPlayer.delegate = self
soundPlayer.prepareToPlay()
soundPlayer.volume = 1.0
}
open func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
playBtn.isEnabled = true
}
open func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
recordBtn.isEnabled = true
playBtn.setTitle("Play", for : .normal)
}
Any help would be greatly appreciated.
UPDATE
Thanks for all your suggestions! I ended up finding the error on another forum here. It appears there needed to be an intermediary between recording and playing the audio called an audio session.
Try initializing the soundPlayer outside of the playSoung method.
var soundPlayer = AVAudioPlayer()
func preparePlayer() {
...
}
It seems that audio file url is nil. Would you try with this FileManager
//func to give path(URL) to store the recording
func getDirectory() -> URL {
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docDirectory = path[0]
return docDirectory
}
And your file URL full path should be:
let path = getDirectory().appendingPathComponent(fileName)
NOTE: As I could not run and test your code, I am not sure of the solution. Let me know the result. Otherwise, I will delete my post.

The sounds work on my Simulator but not on my device... SWIFT

I have a annoying problem with my project here...
When I record something and play it in my Simulator, it's all work fine.
But when I play it in my iPhone the sound don't work... I searched for hours for a solution...
Here's my code
import UIKit
import Parse
import AVFoundation
class View1: UIViewController, AVAudioRecorderDelegate, AVAudioPlayerDelegate {
#IBOutlet weak var recordButton: UIButton!
#IBOutlet weak var playButton: UIButton!
var soundRecorder: AVAudioRecorder!
var soundPlayer:AVAudioPlayer!
let fileName = "sound.caf"
override func viewDidLoad() {
super.viewDidLoad()
setupRecorder()
}
#IBAction func recordSound(sender: AnyObject) {
if (sender.titleLabel?!.text == "Record"){
soundRecorder.record()
sender.setTitle("Stop", forState: .Normal)
playButton.enabled = false
} else {
soundRecorder.stop()
sender.setTitle("Record", forState: .Normal)
}
}
#IBAction func playSound(sender: AnyObject) {
if (sender.titleLabel?!.text == "Play"){
recordButton.enabled = false
sender.setTitle("Stop", forState: .Normal)
preparePlayer()
soundPlayer.play()
} else {
soundPlayer.stop()
sender.setTitle("Play", forState: .Normal)
}
}
// MARK:- AVRecorder Setup
func setupRecorder() {
//set the settings for recorder
let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
AVFormatIDKey : NSNumber(int: Int32(kAudioFormatAppleLossless)),
AVNumberOfChannelsKey : NSNumber(int: 2),
AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Max.rawValue))];
var error: NSError?
do {
// soundRecorder = try AVAudioRecorder(URL: getFileURL(), settings: recordSettings as [NSObject : AnyObject])
soundRecorder = try AVAudioRecorder(URL: getFileURL(), settings: recordSettings)
} catch let error1 as NSError {
error = error1
soundRecorder = nil
}
if let err = error {
print("AVAudioRecorder error: \(err.localizedDescription)")
} else {
soundRecorder.delegate = self
soundRecorder.prepareToRecord()
}
}
// MARK:- Prepare AVPlayer
func preparePlayer() {
var error: NSError?
do {
soundPlayer = try AVAudioPlayer(contentsOfURL: getFileURL())
} catch let error1 as NSError {
error = error1
soundPlayer = nil
}
if let err = error {
print("AVAudioPlayer error: \(err.localizedDescription)")
} else {
soundPlayer.delegate = self
soundPlayer.prepareToPlay()
soundPlayer.volume = 1.0
}
}
// MARK:- File URL
func getCacheDirectory() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory,.UserDomainMask, true)
return paths[0]
}
func getFileURL() -> NSURL {
let path = getCacheDirectory().stringByAppendingString(fileName)
let filePath = NSURL(fileURLWithPath: path)
return filePath
}
// MARK:- AVAudioPlayer delegate methods
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
recordButton.enabled = true
playButton.setTitle("Play", forState: .Normal)
}
func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer, error: NSError?) {
print("Error while playing audio \(error!.localizedDescription)")
}
// MARK:- AVAudioRecorder delegate methods
func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
playButton.enabled = true
recordButton.setTitle("Record", forState: .Normal)
}
func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder, error: NSError?) {
print("Error while recording audio \(error!.localizedDescription)")
}
// MARK:- didReceiveMemoryWarning
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thank you.
add this code in setupRecorder method
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)

Record and play audio Simultaneously

Any one help to me to record and play audio Simultaneously in Iphone.
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.
Please Check aurioTouch apple sample code for audio record-and-play simultaneously
You can also check Recording Audio on an iPhone
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.

Resources