What is an easy way to play a sound clip in an iPhone app?

I want to be able to play a sound clip in an application for iPhone OS. I saw the information on both NSSound and AVFoundation as a tool for receiving sound clips played on the iPhone OS device, but I still do not understand and can use some help. It is not necessary for me to indicate this step by step in the actual code, but if someone can give me a hint about the general direction (that is, which classes I should concentrate) in which I should start moving, I will fill in the forms. So, what is the SIMPLE way to play a sound clip in an iPhone application?

+3
source share
2 answers

Apple has an article on this: this link

AVAudioPlayer is the easiest way to play sounds of any length, loop or not, but it requires iPhone OS 2.2 or higher. A simple example:

NSString *soundFilePath =
                [[NSBundle mainBundle] pathForResource: @"sound"
                                                ofType: @"wav"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

AVAudioPlayer *newPlayer =
                [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                                       error: nil];
[fileURL release];

[newPlayer play];

[newPlayer release];

It will play almost any file format (aiff, wav, mp3, aac). Remember that you can only play one mp3 / aac file at a time.

+8
source

Here is the simplest way I know:

  • Convert the sound file to caf (use the afconvert commandline tool) and add to your project.

    caf means Core Audio Format (I think ...)

  • Look for SoundEffect.h and .m files in the Apple sample. I believe Metronome and BubbleLevel have this.

  • Copy to project
  • Enter the code as shown below:

    SoundEffect *SimpleSound = [[SoundEffect alloc] initWithContentsOfFile:[mainBundle pathForResource:@"soundfile" ofType:@"caf"]];
    [SimpleSound play];
    [SimpleSound release];
    

SoundEffect.m, .

+6

Source: https://habr.com/ru/post/1708868/


All Articles