Search code examples
iosswift3avaudioplayer

Unable to play local mp3 file stored in documents directory using AVAudioPlayer


I have an mp3 audio file generated on an Samsung android device. I download this same file from a server and store in documents directory. Now I use the code below to play this audio file. iAudioFileURL is a property that I use externally to set the audio file url. When the url is set I set up the AVAudioPlayer for that url using the code below

var iAudioFileURL : URL?{
    didSet{
        if let audioFileURL = iAudioFileURL {
            if audioFileURL.isFileURL {
                if let previousURL = iAVAudioPlayer?.url {
                    if previousURL.path == audioFileURL.path {
                        return
                    }
                }

                self.stopPlayer()
                self.iToolBar.items?[0] = iPlayButton

                do {
                    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [AVAudioSessionCategoryOptions.mixWithOthers, AVAudioSessionCategoryOptions.duckOthers])
                    try AVAudioSession.sharedInstance().setActive(true)
                    try iAVAudioPlayer = AVAudioPlayer(contentsOf: audioFileURL)
                } catch  let error as NSError {
                    iError = error
                    return
                }
                iError = nil
                iAVAudioPlayer?.prepareToPlay()
                self.iProgressSlider.minimumValue = 0
                if let duration = self.iAVAudioPlayer?.duration {
                    let durationNumber = NSNumber(floatLiteral: duration)
                    self.iProgressSlider.maximumValue = durationNumber.floatValue
                }
            } else {
                print("Path:\(iAudioFileURL?.path) is not a file url")
            }

        }
    }
}

The code works fine for other files, but for all mp3 files generated from that device fail to play. I have a button which triggers the play method of AVAudioPlayer instance. I have referred most of the questions and answers from stackoverflow. They dont provide me a solution for my case. Even the methods dont throw errors. Please help me out.You can find the file here


Solution

  • The problem was even if the extension was mp3 the mimetype of the file was audio/x-hx-aac-adts. In this thread [https://discussions.apple.com/thread/2365009?tstart=0][1] varjak paw replies

    iTunes, to the best of my knowledge, does not support AAC in ADTS (Audio Data Transport Stream), only AAC in MPEG-4. You'll need to find a converter to get these files into MPEG-4 before iTunes will be able to read them. Sorry, I can't offer any suggestions as to a converter to try.

    Regards.

    So this makes it clear that files with mimetype audio/x-hx-aac-adts are not supported. You can open terminal on mac and use the command below to get mimetypes of files

    file --mime-type -b myfile.extension