Play a short sound in iOS

前端 未结 13 839
悲哀的现实
悲哀的现实 2020-11-27 10:23

I guess I could use AVAudioPlayer to play a sound, however, what I need is to just play a short sound and I don\'t need any loops or fine-grained control over t

13条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 11:03

    A lot of answers are confusing, and some are using the AudioToolbox framework, different from the AVAudioFoundation framework... here's what I did. In the .h file, I put this code in:

    @property (nonatomic, retain) AVAudioPlayer *player;

    This code declares an audio player named "player." In the .m file, under your @implementation declaration, add @synthesize player. This synthesizes that player property.

    In whatever function you want, tie your sound in to the player by adding this line of code, where yourSound is the name of the sound file, and aif is your file extension:

    player = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"yourSound" withExtension:@"aif"] error:nil]

    I know the Apple Documentation says to declare a string and a NSURL, but if you combine it into one line, then you won't have to dispose of it afterwards. Also, since this is a property in your ViewController.m file, then you won't have to keep setting that player object to tie in with your sound.

    Other answers also included using a SystemSoundID, but that also imposes restrictions like, "the file can't be over 30 seconds long," "it has to be in a specific format," and the works. With that, it can play several sounds at a time (in case you're developing a soundboard), and it's easier to create the sounds.

    To actually play your sound, insert this line (and yes, it's really this easy):

    [player play]

    If you use ARC, you can't manually dispose of the player, as the system will do it for you. If you're new to developing and you're using the latest version of Xcode, then you have ARC enabled. If, for some strange reason, you don't, then the code for disposing of the resources being used by player is:

    [player release]

提交回复
热议问题