音频正在模拟器中播放,但不在设备上播放

Audio is playing in simulator but not on device

我正在开发一个播放音频文件的应用程序,并且可以让文件在 xcode 模拟器 (v10.2) 中与 AVPlayer 实例一起播放,但是当尝试在我的设备上播放时音频文件不播放。

我已阅读对同一问题的回复并已检查:

以下是我设置记录器的代码:

func setUpRecorder(storyItem : StoryItem) {

    // Generate unique ID for recording for the StoryItem
    let uuid = UUID().uuidString + ".m4a"

    let audioFileName = getDocumentDirectory().appendingPathComponent(uuid)

    do {
        try self.realm.write {
            // storyItem.recording = audioFileName.absoluteString
            storyItem.recording = uuid
        }
    } catch {
        print("Error saving recording \(error)")
    }
    self.createStoryTableView.reloadData()

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

    do {
        audioRecorder = try AVAudioRecorder(url: audioFileName, settings: recordSettings)
        audioRecorder.delegate = self
        audioRecorder.prepareToRecord()
    } catch {
        print(error)
    }
}

音频文件的播放方法在这里:

func setUpPlayer(storyItem : StoryItem) {

    let audioFileName = getDocumentDirectory().appendingPathComponent(storyItem.recording)

    getAudioDuration(audioFileName: audioFileName)

    if storyItem.recording == "" {

        let alert = UIAlertController(title: "There's no recording", message: "", preferredStyle: .alert)
        let action = UIAlertAction(title: "Cancel", style: .default) { (action) in
        }
        // This is what happens when cancel is pressed

        alert.addAction(action)

        self.present(alert, animated: true, completion: nil)
    } else {

    player = AVPlayer(url: audioFileName)
    player.volume = 1.0

    }
}

如果有任何建议,我将不胜感激。可能是使用唯一标识符(UUID)作为音频文件的名称?

尝试在录制之前配置 AVAudioSession 共享实例。

像这样:

// Configure AVAudioSession
do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch {
    assertionFailure("Failed to configure `AVAAudioSession`: \(error.localizedDescription)")
}