这是由@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
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)
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()
}
}
@IBAction func recordAudio(sender: AnyObject) {
if audioRecorder?.isRecording == false{
playButton.isEnabled = false
stopButton.isEnabled = true
audioRecorder?.record()
}
}
@IBAction func stopAudio(sender: AnyObject) {
stopButton.isEnabled = false
playButton.isEnabled = true
recordButton.isEnabled = true
if audioRecorder?.isRecording == true{
audioRecorder?.stop()
}else{
audioPlayer?.stop()
}
}
@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
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)
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()
}
}
@IBAction func recordAudio(sender: AnyObject) {
if audioRecorder?.isRecording == false{
playButton.isEnabled = false
stopButton.isEnabled = true
audioRecorder?.record()
}
}
@IBAction func stopAudio(sender: AnyObject) {
stopButton.isEnabled = false
playButton.isEnabled = true
recordButton.isEnabled = true
if audioRecorder?.isRecording == true{
audioRecorder?.stop()
}else{
audioPlayer?.stop()
}
}
@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")
}
}