AVAudioPlayer第一次没有正确播放音频

时间:2018-01-23 05:31:40

标签: ios swift audio avaudioplayer avaudiorecorder

我正在开发一个必须播放用户自己录制的音频的项目。当应用程序第一次启动并且用户录制了一些音频时,在尝试播放时,AVAudioPlayer似乎正在播放,但会立即停止播放。如果用户尝试录制另一个音频位,AVAudioPlayer工作正常。

播放和停止音频的代码:

@objc func playAudio() {
    if audioPlayer == nil {
        do{
            if FileManager.default.fileExists(atPath: filename.path) {
                print("File Exists")
            }
            else {
                print("File Doesnt Exists")
            }

            try audioPlayer = AVAudioPlayer(contentsOf: filename)
            audioPlayer.delegate = self
            audioPlayer.prepareToPlay()
            audioPlayer.play()
            print(audioPlayer.isPlaying)
            print("Playing Audio")
            playStopButton.setImage(#imageLiteral(resourceName: "Stop Button"), for: .normal)
        }catch {
            //displayAlert(title: "Oops!", message: "There was an error. Try Recording Again")
            print(error)
        }
    }
    else {
        playStopButton.setImage(#imageLiteral(resourceName: "Play Button"), for: .normal)
        audioPlayer.stop()
        audioPlayer = nil
    }
}

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    if flag {
        print("Stopping Cuase Comlete")
        playStopButton.setImage(#imageLiteral(resourceName: "Play Button"), for: .normal)
        audioPlayer.stop()
        audioPlayer = nil
    }
}

录制音频的代码

@objc func record() {

    if audioRecorder == nil{

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

        do{
            audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
            audioRecorder.delegate = self
            audioRecorder.record()
            //view.backgroundColor = UIColor.red
            //recordButton.setTitle("Stop Recording", for: .normal)
            setupTimer()
            timerDisplay.isHidden = false
            shapeLayer.fillColor = UIColor.black.cgColor

        }catch{
            displayAlert(title: "Oops!", message: "Recording Failed")
        }
    }
    else{
        audioRecorder.stop()
        timer?.invalidate()
        timer = nil
        shapeLayer.strokeEnd = 0
        audioRecorder=nil;

        timerDisplay.isHidden = true
        shapeLayer.fillColor = UIColor.red.cgColor
        let selected = arr[picker.selectedRow(inComponent: 0)]
        UserDefaults.standard.set(selected, forKey: "SelectedTopic")

        present(UINavigationController(rootViewController: PlaybackController()), animated: true, completion: nil)
    }
}

1 个答案:

答案 0 :(得分:4)

在Audiorecorder上也遇到了同样的问题。我通过设置播放器的方法来解决此问题。像这样:

func setupView() {
        recordingSession = AVAudioSession.sharedInstance()

        do {
            try recordingSession.setCategory(.playAndRecord, mode: .default)
            try recordingSession.setActive(true)
            recordingSession.requestRecordPermission() { [unowned self] allowed in
                DispatchQueue.main.async {
                    if allowed {
                        self.loadRecordingUI()
                    } else {
                        // failed to record
                    }
                }
            }
        } catch {
            // failed to record
        }
    }

,然后在我的viewDidLoad.as中调用它:

self.setupView()