问题
I have an instance of AVAudioPlayer that will play several sounds. Is there a way to provide an AVAudioPlayer instance with a new sound, or do I have to create a new instance with initWithData:?
回答1:
Reusing objects is usually a bad idea, generally try to have your objects as short-lived as possible. This reduces the number of possible states of your code and makes reasoning about it easier. (“Where did this value come from? Maybe it’s a leftover from the previous instance usage?” Yuck.) Only break this rule once you run into measurable problems.
For further reading along this line of thought you can browse questions tagged “immutable”.
回答2:
There's no API to pass a new file to an existing AVAudioPlayer instance. However, AVAudioPlayer creation isn't expensive, so you shouldn't be concerned about performance, as long as you release instances once you're done with them.
If you have a fixed set of sounds that play over each other, or are likely to play repeatedly, you can create one AVAudioPlayer instance for each sound and re-use those instances by calling play on the appropriate instance.
If only one sound is playing at a time, and you're generating new sounds (for instance with text-to-speech based on user input), I generally have a single player as a property. When a new sound plays, I call [player stop], release the old player, and instantiate a new one with the new sound file.
来源:https://stackoverflow.com/questions/6452056/reusing-an-avaudioplayer-for-a-different-sound