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.
Related
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)
}
}
}
I saw a lot of tutorials but when i click button (that actvivate The func playsound) The sound doesn’t play. I saw the code reccomended by stackoverflow but nothing.
I put The mp3 file info asset.xcasset. It’s right?
SWIFT 4 / XCODE 9.1
import AVFoundation
var objPlayer: AVAudioPlayer?
func playAudioFile() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
// For iOS 11
objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
// For iOS versions < 11
objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)
guard let aPlayer = objPlayer else { return }
aPlayer.play()
} catch let error {
print(error.localizedDescription)
}
}
SWIFT 4.2 / XCODE 10.1
Note that you must call
AVAudioSession.sharedInstance().setCategory() with the mode parameter in Swift 4.2.
import AVFoundation
var audioPlayer: AVAudioPlayer?
func playSound() {
if let audioPlayer = audioPlayer, audioPlayer.isPlaying { audioPlayer.stop() }
guard let soundURL = Bundle.main.url(forResource: "audio_file", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
audioPlayer?.play()
} catch let error {
Print.detailed(error.localizedDescription)
}
}
A very simple solution.
import AVFoundation
var myAudioPlayer = AVAudioPlayer?
func playAudioFile() {
let audioFileURL = Bundle.main.url(forResource: "<name-of-file>", withExtension: "mp3/wav/m4a etc.")
do {
try myAudioPlayer = AVAudioPlayer(contentsOf: audioFileURL!)
} catch let error {
print(error.localizedDescription)
}
myAudioPlayer?.play()
}
Now, play this audio file anywhere by calling: playAudioFile()
Add your .mp3 file to Bundle
import AVFoundation
let url = Bundle.main.url(forResource: "SampleAudio", withExtension: "mp3")
let playerItem = AVPlayerItem(url: url!)
let player=AVPlayer(playerItem: playerItem)
let playerLayer=AVPlayerLayer(player: player)
playerLayer.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
self.view.layer.addSublayer(playerLayer)
player.play()
You can also put a timer to show the progress of the music played
import AVFoundation
class ViewController: UIViewController {
var player : AVAudioPlayer?
var timer : Timer?
#IBOutlet var pauseBtn: UIButton!
#IBOutlet var replayBtn: UIButton!
#IBAction func rewind2(_ sender: Any) {
}
#IBAction func forward(_ sender: Any) {
var time : TimeInterval = (player?.currentTime)!
time += 5.0
if (time > (player?.duration)!)
{
// stop, track skip or whatever you want
}
else
{
player?.currentTime = time
}
}
#IBOutlet var progress: UIProgressView!
#IBAction func playClicked(_ sender: Any) {
if player == nil {
let resource = Bundle.main.url(forResource: "audioFX", withExtension: "mp3")
do {
player = try AVAudioPlayer(contentsOf: resource!)
player?.isMeteringEnabled = true
player?.prepareToPlay()
} catch let error {
print(error)
}
}
if player != nil {
player?.play()
enableTimer()
player!.delegate = self as? AVAudioPlayerDelegate
}
}
#IBAction func pauseClicked(_ sender: Any) {
if(player != nil){
if(player?.isPlaying == true){
endTimer()
player!.pause()
pauseBtn.setTitle("Resume", for: .normal)
}else{
player!.play()
enableTimer()
pauseBtn.setTitle("Stop", for: .normal)
}
}
}
#IBAction func replayClicked(_ sender: Any) {
if player != nil{
endTimer()
player = nil
pauseBtn.setTitle("Stop", for: .normal)
playClicked(replayBtn)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func enableTimer(){
if(player != nil){
timer = Timer(timeInterval: 0.1, target: self, selector: (#selector(self.updateProgress)), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: RunLoopMode(rawValue: "NSDefaultRunLoopMode"))
}
}
func endTimer(){
if(timer != nil){
timer!.invalidate()
}
}
#objc func updateProgress(){
if(player != nil){
player!.updateMeters() //refresh state
progress.progress = Float(player!.currentTime/player!.duration)
}
}
}
Simple way with Swift 4.2:
import AVFoundation
and
let soundEffect = URL(fileURLWithPath: Bundle.main.path(forResource: "btn_click_sound", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
#IBAction func buttonClick(sender: AnyObject) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundEffect)
audioPlayer.play()
} catch {
// couldn't load file :(
}
}
When I run below code, I get this error Domain=NSOSStatusErrorDomain Code=1718449215 "(null)"
Error in prepare audio recorder
Error Domain=NSOSStatusErrorDomain Code=1718449215 "(null)"
Error in prepare audio recorder
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var recordAoutlet: UIButton!
#IBOutlet weak var playOutlet: UIButton!
var audioRecorder:AVAudioRecorder!
var audioPLayer:AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.prepareAudioRecorder()
}
#IBAction func recorderAction(_ sender: AnyObject) {
if !audioRecorder.isRecording {
//Start Recorder
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setActive(true)
audioRecorder.record()
} catch{
print(error.localizedDescription)
print("error in recorder action 1")
}
} else {
//Stop Recorder
audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setActive(false)
}catch {
print(error.localizedDescription)
print("error in recorder action 2")
}
//check
if self.verifyFileExists() {
print("file exixts")
playOutlet.isHidden = false
} else {
print("there was a problem recording.")
}
}
self.updateRecorderbuttonTitle()
}
#IBAction func playAction(_ sender: AnyObject) {
self.playAudio()
}
//MARK: main
func prepareAudioRecorder() {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioRecorder = AVAudioRecorder(url: URL(fileURLWithPath: self.audioFileLocation()), settings: self.audioSettings())
audioRecorder.prepareToRecord()
} catch {
print(error)
print("Error in prepare audio recorder")
}
}
func playAudio(){
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
try audioPLayer = AVAudioPlayer(contentsOf: URL(fileURLWithPath:self.audioFileLocation()))
audioPLayer.prepareToPlay()
audioPLayer.play()
} catch {
print(error)
print("error in audio session func")
}
}
// MARK:Helper
func audioFileLocation()-> String {
return NSTemporaryDirectory().appending("AudioRecording.mp4")
}
func audioSettings()->[String:Any] {
let settings = [AVFormatIDKey : NSNumber.init(value: kAudioFormatAppleLossless),
AVSampleRateKey : NSNumber.init(value: 44100.0),
AVNumberOfChannelsKey : NSNumber.init(value: 1),
AVLinearPCMBitDepthKey : NSNumber.init(value: 16),
AVEncoderAudioQualityKey : NSNumber.init(value: AVAudioQuality.high.rawValue)]
return settings
}
// update buttons titles
func updateRecorderbuttonTitle(){
if audioRecorder.isRecording {
recordAoutlet.setTitle("Recording...", for:.normal)
} else {
recordAoutlet.setTitle("Record", for: .normal)
}
}
// Verify File Exists
func verifyFileExists()-> Bool{
let fileManager = FileManager.default
return fileManager.fileExists(atPath: self.audioFileLocation())
}
}
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
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)