0

Trying play AMR audio file using this code:

    var player: AVAudioPlayer? = nil
    WebService.shared.download(self.dataSource.object(at: indexPath)) { data in
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)

            player = try AVAudioPlayer(data: data, fileTypeHint: AVFileType.amr.rawValue)
            guard let player = player else { return }

            print("Going to play: \(player.duration) seconds...")
            player.volume = 1.0
            player.prepareToPlay()
            player.play()
        } catch {
            print(error.localizedDescription)
        }
    }

I'm absolutely sure that:

  1. data received is not nil
  2. I can see correct duration time of amr file
  3. amr files contains some voices
  4. I did not get any error's
  5. I did not hear anything

What's up and how fix it?

zzheads
  • 1,368
  • 5
  • 28
  • 57

1 Answers1

1

The problem is with

guard let player = player else { return }

You are replacing the outer, optional AVAudioPlayer with a non-optional local copy. You call play() on the local copy and then when the closure completes, it goes out of scope and is deleted.

Try this.

    player = try AVAudioPlayer(data: data, fileTypeHint: AVFileType.amr.rawValue)
    player?.volume = 1.0
    player?.prepareToPlay()
    player?.play()
} catch {
Price Ringo
  • 3,424
  • 1
  • 19
  • 33
  • But what a problem? I'm using player only inside closure – zzheads Oct 04 '17 at 15:45
  • Replaced with: let player = try AVAudioPlayer(data: data, fileTypeHint: AVFileType.amr.rawValue) print("Going to play: \(player.duration) seconds ...") player.volume = 1.0 player.prepareToPlay() player.play() . Same result – zzheads Oct 04 '17 at 15:50
  • That won't work. Remove the let in front of the let player = AV... Don't create a local variable. Use the player variable declared above your webservice. – Price Ringo Oct 04 '17 at 16:00
  • That was a decision of half a problem. Now I can play .wav, .mp3, .ac, etc. audio, but not .amr. – zzheads Oct 06 '17 at 21:01