Reputation: 345
I am developing an audio app which needs to play two data (ex: dataA and dataB). For the purpose of the app, it should play the audio data in this order:
| dataA | dataB | dataB | ...... repeat N times of data B ... |
An easy solution of it would be creating a super large NSData that contains the above data structures (1 dataA + N dataB). However, it is inefficient, especially when N > 10000.
In Android or other systems that I can directly control the audio play buffer, I can simply push dataA to the play buffer and then have a for loop to put dataB as many times as I want (without allocating a super-large buffer to save the repetition of dataB).
How can it be achieved by AVAudioPlayer? (NOTE: for the purpose of the app, I need the dataB being played directly after dataA with 0 delay. So it is impossible to use multiple AVAudioPlayer classes)
Upvotes: 0
Views: 66
Reputation: 20379
create two AVPlayer instances, one for playing aData and one for playing bData.
let aDataPlayer = AVPlayer(url: URL(string: aData_URL)!)
let bDataPlayer : AVPlayer? = nil
var counterForbPlayer : Int = 100 //whatever your n value is
use AVPlayerItemDidPlayToEndTime
to get notified when a player finishes playing.
NotificationCenter.default.addObserver(self, selector: #selector(loadNextudio), name: .AVPlayerItemDidPlayToEndTime, object: nil)
func loadNextudio() {
if self.bDataPlayer == nil {
bDataPlayer = AVPlayer(url: URL(string: bData_URL)!)
bDataPlayer.play()
counterForbPlayer -= 1;
}
else {
if counterForbPlayer > 0 {
bDataPlayer?.currentItem?.seek(to: kCMTimeZero)
bDataPlayer?.play()
counterForbPlayer -= 1;
}
}
}
Upvotes: 1