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:?
2 Answers
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.

- 17,523
- 6
- 79
- 92
-
2Yeah, I searched Google for this question because I thought making a lot of new AVAudioPlayer would cause performance degradation. Your answer solves my questions at once. 1)No way to modify file in AVAudioPlayer 2)Creating AVAudioPlayer is not expensive. – Damn Vegetables Aug 19 '12 at 10:58
-
Any suggestions under ARC? – Piper Jun 24 '13 at 19:06
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”.
-
18This isn't an answer to @Fernando's question, and is an over-generalization. There are many contexts where object reuse is a better approach than new object creation. – Christopher Pickslay Jun 24 '11 at 16:53
-
1I think Christopher is right. It is for performance reasons. For example, table view reuses existing cells and Apple explicitly encourages it. At least you had answered to the posters question, "there is no way to change the file" as Christopher did. – Damn Vegetables Aug 19 '12 at 10:56
-
Table view is a special case because it has to meet hard performance requirements (scrolling). But generally the performance cost of a new object construction is quite low today and I stand by the statement that it’s a bad idea to reuse objects until hitting a performance problem. – zoul Aug 21 '12 at 08:37