Reusing an AVAudioPlayer for a different sound

ぃ、小莉子 提交于 2019-12-04 20:04:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!