WatchKit AVAudioRecorder: приложение записи не записывает - PullRequest
0 голосов
/ 13 января 2020

Я хочу иметь приложение для часов, которое делает записи пользователя. Я добавил свойство NSMicrophoneUsageDescription как в приложение ios, так и в расширение watchkit infoplist, однако приглашение для доступа к микрофону не отображается. Я также добавил функцию вызова requestRecordPermission(). Приложение записи не работает вообще, когда я запускаю приложение на реальном устройстве наблюдения. Я не знаю, в чем здесь проблема, кто-нибудь может просмотреть?

Большое спасибо.

Вот код для InterfaceController:

import WatchKit
import Foundation
import AVFoundation


class InterfaceController: WKInterfaceController, AVAudioRecorderDelegate{

    var recordSession: AVAudioSession!
    var audioRecorder: AVAudioRecorder!
    var settings = [String : Int]()

    @IBOutlet weak var recordBtn: WKInterfaceButton!
    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        print("Hello Test")
        recordSession = AVAudioSession.sharedInstance()

        do{
            try recordSession.setCategory(AVAudioSession.Category.playAndRecord)
            try recordSession.setActive(true)
            recordSession.requestRecordPermission(){[unowned self] allowed in
                DispatchQueue.main.async{
                    if allowed{
                        print("Allow recording!")
                    } else{
                        print("Do not allow recording!")
                    }
                }

            }
        }catch{
            print("Recording failed!")
        }

        // configure audio settings
        settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                               AVSampleRateKey: 12000,
                               AVNumberOfChannelsKey: 1,
                               AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
                               ]
    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }

    func getDocumentsDirectory()-> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentDirectory = paths[0]
        let audioPath = documentDirectory.appendingPathComponent("recording.m4a")
        return audioPath
    }

    func startRecording(){
        let soundSession = AVAudioSession.sharedInstance()

        do{
            audioRecorder = try AVAudioRecorder(url:self.getDocumentsDirectory(),settings:settings)
            audioRecorder.delegate = self
            audioRecorder.prepareToRecord()
        }catch{
            finishRecording(success: false)
        }

        do{
            try soundSession.setActive(true)
            audioRecorder.record()
        }catch{
            print("Inactive session")
        }
    }

    func finishRecording(success: Bool){
        audioRecorder.stop()
        if success{
            print("Recorded successfully!")
        }else{
            audioRecorder = nil
            print("Recording failed!")
        }
        // setting audioRecorder to nil??
    }

    @IBAction func recordListener() {
        print("Button clicked!")
        if audioRecorder == nil{
            self.startRecording()
        }else{
            self.finishRecording(success: true)
        }
    }

    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        if !flag{
            finishRecording(success:false)
        }
    }
}

Вот весь проект:

https://gofile.io/?c=3fqN1R

...