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

Zen*_*n C 2 m4a avplayer swift

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

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

  • 设备上的静音铃声开关未打开
  • 我没有在 viewDidLoad 中实例化 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*iki 5

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

像这样:

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