录音机应用程序仅在Swift中播放最后保存的记录URL

时间:2018-07-11 09:03:05

标签: ios swift avaudioplayer avaudiorecorder

有一个此应用程序,您可以在其中添加多个录音机,其想法是让每个录音机都通过自己的按钮播放录制的音频。看到那里有“加号”按钮,它以编程方式添加了UI。我在这里提供了一张图片,供您更好地理解:

Audio recorder essentials added to the green superview

无论按钮代表其应有的功能,但是录制的音频文件都会出现此问题,无论在主(紫色)屏幕中嵌入多少个录音机视图,它始终播放最后一个不相关的URL使用哪个记录器。例如,我使用第一台录音机录制5秒长的音频,第二台录制3秒,第三台录制9声,每个录音机的“播放”按钮都播放9秒,因为这是最后添加的。

我的代码在下面,我尝试在每个部分下添加有意义的注释:

private var soundFileURL: URL!
private var recorder: AVAudioRecorder!
private var player: AVAudioPlayer!

//This function is used for play button
func play() {
    print("\(#function)")

    var url: URL?
    if self.recorder != nil {
        url = self.recorder.url
    } else {
        url = self.soundFileURL!
    }

    do {
        self.player = try AVAudioPlayer(contentsOf: url!)
        stopButton.isEnabled = true
        player.delegate = self
        player.prepareToPlay()
        player.volume = 1.0
        player.play()
    } catch {
        self.player = nil
        print(error.localizedDescription)
    }
}

//The function that does the recording
func setupRecorder() {
    print("\(#function)")

    let format = DateFormatter()
    format.dateFormat="yyyy-MM-dd-HH-mm-ss"
    let currentFileName = "recording-\(format.string(from: Date())).m4a"
    print(currentFileName)

    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    self.soundFileURL = documentsDirectory.appendingPathComponent(currentFileName)
    print("writing to soundfile url: '\(soundFileURL!)'")

    if FileManager.default.fileExists(atPath: soundFileURL.absoluteString) {
        //Probably won't happen because the currentFileName is always unique
        print("soundfile \(soundFileURL.absoluteString) exists")
    }

    let recordSettings: [String: Any] = [
        AVFormatIDKey: kAudioFormatAppleLossless,
        AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue,
        AVEncoderBitRateKey: 32000,
        AVNumberOfChannelsKey: 2,
        AVSampleRateKey: 44100.0
    ]


    do {
        recorder = try AVAudioRecorder(url: soundFileURL, settings: recordSettings)
        recorder.delegate = self
        recorder.isMeteringEnabled = true
        recorder.prepareToRecord() // creates/overwrites the file at soundFileURL
    } catch {
        recorder = nil
        print(error.localizedDescription)
    }
}

由于我怀疑它可能会受到以编程方式添加的视图的影响,因此,如果需要重构,我将在此处发布代码:

@IBAction func addVoiceRecorder(_ sender: UIButton) {
    let voiceView = ResizeViews(frame: CGRect(x: stableX, y: stableY , width: 250, height: 70)) //ResizeViews is a custom class made for views alike in this app
    voiceView.backgroundColor = UIColor.green
    voiceView.layer.cornerRadius = 0
    voiceView.layer.borderWidth = 2
    voiceView.layer.borderColor = UIColor.red.cgColor

    scrollView.addSubview(voiceView) //This is the master view, the purple one in the picture.

        //The rest of the code is rather ignorable because it is mainly about constraints and the buttons added. I will only put one of the buttons configuration in here.
        recordButton = UIButton(frame: CGRect(x: voiceView.frame.width - 60, y: voiceView.frame.height - ((voiceView.frame.height / 2) + 25), width: 50, height: 50))
        recordButton.backgroundColor = .clear
        //recordButtonPressed is an @objc method which directly uses the recorder function I have posted earlier 
        recordButton.addTarget(self, action: #selector(recordButtonPressed(sender:)), for: .touchUpInside)

    voiceView.addSubview(recordButton)

    setupRecorder()

}

我认为字典或数组可以完成这项工作,但我自己无法完成。不得不说这只是一个离线项目,不可能使用在线工具保存数据。

0 个答案:

没有答案