斯威夫特:播放录制的音频

时间:2015-07-30 10:32:56

标签: ios swift audio

我试着录音,我可以在这里找到一个好的答案: Recording audio in Swift

我可以让它发挥作用。但现在我想知道如何播放录制的音频。从录制中我已经有了一般的var audioRecorder,并定义了url路径。所以我尝试了audioRecorder.play(),但它不起作用。

我认为这个问题来自于全局var audioRecorder是AVAudioRecorder的一个实例并且如果它是AVAudioPlayer的一个实例就播放它,这两个东西是如何相关的?

我不想复制粘贴我想了解的代码。这就是我在这里简化代码的原因。请解释为什么它在这个特定代码中不起作用以及如何解决它。

(我已经做了很多相关的教程。问题是我丢失了很多代码。我的问题是要了解这个特定部分是如何工作的)

import AVFoundation
var audioRecorder:AVAudioRecorder!
@IBAction func record(sender: AnyObject) {       
    var audioSession:AVAudioSession = AVAudioSession.sharedInstance()
    audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
    audioSession.setActive(true, error: nil)

    var documents: AnyObject = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory,  NSSearchPathDomainMask.UserDomainMask, true)[0]
    var str =  documents.stringByAppendingPathComponent("recordTest.caf")
    var url = NSURL.fileURLWithPath(str as String)
    println(url)

    audioRecorder = AVAudioRecorder(URL:url, settings: nil, error: nil)
    audioRecorder.record()
}

@IBAction func play(sender: AnyObject) {
   // this gives the error 'AVAudioRecorder' does not have a member named 'play'
   // audioRecorder.play() 
}

2 个答案:

答案 0 :(得分:2)

以下是录制音频的完整工作代码,然后将其存储到文件然后播放:

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.enabled = false
        stopButton.enabled = false

        // getting URL path for audio
        let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let docDir = dirPath[0] as! String
        let soundFilePath = docDir.stringByAppendingPathComponent("sound.caf")
        let soundFileURL = NSURL(fileURLWithPath: soundFilePath)
        println(soundFilePath)

        //Setting for recorder
        let recordSettings = [AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue,
            AVEncoderBitRateKey: 16,
            AVNumberOfChannelsKey : 2,
            AVSampleRateKey: 44100.0]
        var error : NSError?
        let audioSession = AVAudioSession.sharedInstance()
        audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: &error)
        if let err = error{
            println("audioSession error: \(err.localizedDescription)")
        }
        audioRecorder = AVAudioRecorder(URL: soundFileURL, settings: recordSettings as [NSObject : AnyObject], error: &error)

        if let err = error{
            println("audioSession error: \(err.localizedDescription)")
        }else{
            audioRecorder?.prepareToRecord()
        }
    }
    //record audio
    @IBAction func recordAudio(sender: AnyObject) {

        if audioRecorder?.recording == false{
            playButton.enabled = false
            stopButton.enabled = true
            audioRecorder?.record()
        }
    }
    //stop recording audio
    @IBAction func stopAudio(sender: AnyObject) {

        stopButton.enabled = false
        playButton.enabled = true
        recordButton.enabled = true

        if audioRecorder?.recording == true{
            audioRecorder?.stop()
        }else{
            audioPlayer?.stop()
        }
    }
    //play your recorded audio
    @IBAction func playAudio(sender: AnyObject) {

        if audioRecorder?.recording == false{
            stopButton.enabled = true
            recordButton.enabled = false

            var error : NSError?

            audioPlayer = AVAudioPlayer(contentsOfURL: audioRecorder?.url, error: &error)

            audioPlayer?.delegate = self

            if let err = error{
                println("audioPlayer error: \(err.localizedDescription)")
            }else{
                audioPlayer?.play()
            }
        }
    }

    func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
        recordButton.enabled = true
        stopButton.enabled = false
    }

    func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!) {
        println("Audio Play Decode Error")
    }

    func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) {
    }

    func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder!, error: NSError!) {
        println("Audio Record Encode Error")
    }
}

检查THIS示例项目以获取更多信息。

在您的代码中,audioRecorder用于录制音频,audioPlayer用于播放音频。这就是audioRecorder没有财产play()

的原因

因此您无法使用audioRecorder.play()

答案 1 :(得分:0)

这是@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")
    }
}