这是@DharmeshKheni 的答案 + 为 swift 4.0 更新
创建三个按钮并向它们添加插座和方法。
新版本
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate {
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var stopButton: UIButton!
@IBOutlet weak var playButton: UIButton!
var audioPlayer : AVAudioPlayer?
var audioRecorder : AVAudioRecorder?
override func viewDidLoad() {
super.viewDidLoad()
playButton.isEnabled = false
stopButton.isEnabled = false
// getting URL path for audio
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let docDir = dirPath[0]
let soundFilePath = (docDir as NSString).appendingPathComponent("sound.caf")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath)
print(soundFilePath)
//Setting for recorder
let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.min.rawValue,
AVEncoderBitRateKey: 16,
AVNumberOfChannelsKey : 2,
AVSampleRateKey: 44100.0] as [String : Any] as [String : Any] as [String : Any] as [String : Any]
var error : NSError?
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSession.Category.playAndRecord)
audioRecorder = try AVAudioRecorder(url: soundFileURL as URL, settings: recordSettings as [String : AnyObject])
} catch _ {
print("Error")
}
if let err = error {
print("audioSession error: \(err.localizedDescription)")
}else{
audioRecorder?.prepareToRecord()
}
}
//record audio
@IBAction func recordAudio(sender: AnyObject) {
if audioRecorder?.isRecording == false{
playButton.isEnabled = false
stopButton.isEnabled = true
audioRecorder?.record()
}
}
//stop recording audio
@IBAction func stopAudio(sender: AnyObject) {
stopButton.isEnabled = false
playButton.isEnabled = true
recordButton.isEnabled = true
if audioRecorder?.isRecording == true{
audioRecorder?.stop()
}else{
audioPlayer?.stop()
}
}
//play your recorded audio
@IBAction func playAudio(sender: AnyObject) {
if audioRecorder?.isRecording == false{
stopButton.isEnabled = true
recordButton.isEnabled = false
var error : NSError?
do {
let player = try AVAudioPlayer(contentsOf: audioRecorder!.url)
audioPlayer = player
} catch {
print(error)
}
audioPlayer?.delegate = self
if let err = error{
print("audioPlayer error: \(err.localizedDescription)")
}else{
audioPlayer?.play()
}
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
recordButton.isEnabled = true
stopButton.isEnabled = false
}
private func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!) {
print("Audio Play Decode Error")
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
}
private func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder!, error: NSError!) {
print("Audio Record Encode Error")
}
}
旧版本
import UIKit
import AVFoundation
class PlayVC: UIViewController, AVAudioPlayerDelegate, AVAudioRecorderDelegate {
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var stopButton: UIButton!
@IBOutlet weak var playButton: UIButton!
var audioPlayer : AVAudioPlayer?
var audioRecorder : AVAudioRecorder?
override func viewDidLoad() {
super.viewDidLoad()
playButton.isEnabled = false
stopButton.isEnabled = false
// getting URL path for audio
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let docDir = dirPath[0] as! String
let soundFilePath = docDir.stringByAppendingPathComponent(path: "sound.caf")
let soundFileURL = NSURL(fileURLWithPath: soundFilePath)
print(soundFilePath)
//Setting for recorder
let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.min.rawValue,
AVEncoderBitRateKey: 16,
AVNumberOfChannelsKey : 2,
AVSampleRateKey: 44100.0] as [String : Any]
var error : NSError?
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch {
print(error)
}
if let err = error{
print("audioSession error: \(err.localizedDescription)")
}
do {
audioRecorder = try AVAudioRecorder(url: soundFileURL as URL, settings: recordSettings as [String : Any])
} catch {
print(error)
}
if let err = error{
print("audioSession error: \(err.localizedDescription)")
}else{
audioRecorder?.prepareToRecord()
}
}
//record audio
@IBAction func recordAudio(sender: AnyObject) {
if audioRecorder?.isRecording == false{
playButton.isEnabled = false
stopButton.isEnabled = true
audioRecorder?.record()
}
}
//stop recording audio
@IBAction func stopAudio(sender: AnyObject) {
stopButton.isEnabled = false
playButton.isEnabled = true
recordButton.isEnabled = true
if audioRecorder?.isRecording == true{
audioRecorder?.stop()
}else{
audioPlayer?.stop()
}
}
//play your recorded audio
@IBAction func playAudio(sender: AnyObject) {
if audioRecorder?.isRecording == false{
stopButton.isEnabled = true
recordButton.isEnabled = false
var error : NSError?
do {
audioPlayer = try AVAudioPlayer(contentsOf: (audioRecorder?.url)!)
} catch {
print(error)
}
audioPlayer?.delegate = self
if let err = error{
print("audioPlayer error: \(err.localizedDescription)")
}else{
audioPlayer?.play()
}
}
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
recordButton.isEnabled = true
stopButton.isEnabled = false
}
func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!) {
print("Audio Play Decode Error")
}
func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) {
}
func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder!, error: NSError!) {
print("Audio Record Encode Error")
}
}