AVAUdioPlayer - change the current URL

In the application for the audio player, if I press the fast forward button, the player should find the next song in the playlist and play it. What I am doing is getting the URL from the next song and trying to put it in the background (the background is an instance of the AVAudioPlayer * field), but this property is read-only. So what I'm actually doing is I call the initWithContentsOfURL method (again) to set the URL as follows:

[self.background initWithContentsOfURL: [[_playlist.collection objectAtIndex:currentIndex] songURL] error:nil]; 

It is legal? I mean, the compiler tells me that the result of the expression is not used, but it really works. Is there any other way to do this? Thanks; -)

+4
source share
2 answers

Selected 4 samples of Apple, they use AVAudioPlayer to play only one song. However, your result looks very interesting and impressive! Let us know if you stop playback before reinitializing the object with the same address, are you starting a new audio session?

As for me, I would not put the stability of the playback and the application at risk of doing something not mentioned in the documentation, but, to be on the bright side, I will use the AVAudioPlayer class, since it seems to be the most correct, which gives us:

  • Use the error variable to track possible errors.
  • stop the instance of the AVAudioPlayer player, initialize a new instance of AVAudioPlayer and set it to a property that allows the old person to be freed automatically.

And you probably know yourself that

 self.background = [self.background initWithContentsOfURL:: 

will remove the warning for you.

+4
source

To play back more than one URL or efficiently change the URL, use the AVQueuePlayer subclass.

AVQueuePlayer is a subclass of AVPlayer that you use to play multiple items sequentially.

Example:

 NSString *fooVideoPath = [[NSBundle mainBundle] pathForResource:@"tommy" ofType:@"mov"]; NSString *barVideoPath = [[NSBundle mainBundle] pathForResource:@"pamela" ofType:@"mp4"]; AVPlayerItem *fooVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:fooVideoPath]]; AVPlayerItem *barVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:barVideoPath]]; self.queuePlayer = [AVQueuePlayer queuePlayerWithItems:[NSArray arrayWithObjects:fooVideoItem, barVideoItem,nil]]; [self.queuePlayer play]; // things happening... [self.queuePlayer advanceToNextItem]; 
+17
source

Source: https://habr.com/ru/post/1401482/


All Articles