Search code examples
swiftavplayerm4a

Audio is playing in simulator but not on device


I'm developing an app that plays audio files and can get the files to play with an instance of AVPlayer in the xcode simulator (v10.2) but when trying to play this on my device the audio file does not play.

I have read responses to the same issue and have checked:

  • that the mute ringer switch on the device is not turned on
  • that I have not instantiated the AVPlayer in the viewDidLoad
  • that the name of the audio file is the same case in the code as in the file

Following is the code where I set up the recorder:

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)
    }
}

Method for playing the audio file is here:

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

    }
}

I'd be grateful for any suggestions. Could it be the use of the unique identifier (UUID) as the name of the audio file?


Solution

  • Try to configure AVAudioSession shared instance prior to recording.

    Like this:

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