Max Lukin
Max Lukin

Reputation: 135

AVPlayer doesn't play more than one time

I have some strange problem with playing audio through AVPlayerItem & AVPlayer.

I have recorder and iPod item picker, stream from both of them are going through code like this:

  AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
  [audioSession setActive:YES error:nil];

  _playerItem = [[AVPlayerItem alloc] initWithURL:_soundFileURL];
  _player = [[AVPlayer alloc] initWithPlayerItem:_playerItem];
  [_player play];

Everything is actually ok, except one thing, I can't play this stream second or more time. It's just stopped, and no sounds are found after stopping. Does anybody can help with an advice, what the problem could be?

Upvotes: 6

Views: 3050

Answers (3)

Golden Thumb
Golden Thumb

Reputation: 2571

Here is what happens on my Swift 5, Xcode 12, macOS 11, iOS 14.2 combination:

  • I only play a short drop.wav sound for dropping a piece on game board
  • a few months ago player.play() worked for my environment with lower versions
  • today player.play() plays only once, dropping the next piece is silent
  • adding player.seek(to: CMTime.zero) "works", but only the first time it sounds normal, the 2nd, 3rd ... time the sound is different, weaker
  • my workaround is reloading the sound file every time before playing it
  • I recorded a video for this experiment https://youtu.be/t6863IZkwTQ

Upvotes: 0

Nazrul Islam
Nazrul Islam

Reputation: 768

In Swift 4

You can use below line to play again.

self.player?.seek(to: CMTime.zero)
self.player?.play()

Happy to help :)

Upvotes: 6

IanStallings
IanStallings

Reputation: 816

You have to set the AVPlayer back to beginning of the stream using prepareToPlay and setting the currentPlaybackTime to 0.

self.avPlayer.currentPlaybackTime = 0;
[self.avPlayer prepareToPlay];

Upvotes: 6

Related Questions