Best method to play an short audio sound on iOS 8.2
Asked Answered
D

3

9

What is the best way to play an audio on iOS 8.2?

Dulcle answered 11/3, 2015 at 11:52 Comment(1)
how about AVAudioPlayer ?Commercialize
R
18

The easiest way is to import the AudioToolbox framework like so #import <AudioToolbox/AudioToolbox.h> then all you need to do is this:

NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Beep" ofType:@"mp3"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundPath], &soundID);
AudioServicesPlaySystemSound(soundID);

This is best for really short sounds like beeps e.t.c because you wont have much control over the sounds like you would with AVAudioPlayer.

Ruvalcaba answered 11/3, 2015 at 15:0 Comment(2)
Thanks. Seem that for short sounds this is the best method.Dulcle
mp3 interrupts other sounds and cannot be played with others. You might need caf instead.Chainplate
U
10

Use AVAudio - more to code that using the AudioToolbox but it is also more flexible (if you need it in the future)

0.

#import <AVFoundation/AVFoundation.h>

1.

//conform to delegate and make a property
@interface ViewController () <AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *audioplayer; //the player
@end

2.

//have a lazy property for the player! where you also tell it to load the sound
#define YourSound @"sound.caf"
- (AVAudioPlayer *)audioplayer {
    if(!_audioplayer) {
        NSURL *audioURL = [[NSBundle mainBundle] URLForResource:YourSound.stringByDeletingPathExtension withExtension:YourSound.pathExtension];
        NSData *audioData = [NSData dataWithContentsOfURL:audioURL];
        NSError *error = nil;
        // assing the audioplayer to a property so ARC won't release it immediately
        _audioplayer = [[AVAudioPlayer alloc] initWithData:audioData error:&error];
        _audioplayer.delegate = self;
    }
    return _audioplayer;
}

3.

//play
- (void)action {
    [self.audioplayer play];
}
Uribe answered 11/3, 2015 at 15:4 Comment(1)
Thanks, it works for me. But for short audios I will try the C functions.Dulcle
G
2
#Import Avfoundation.Framework

AVAudioPlayer *_audioPlayer;  //Declare Globally

Nsstring *path =[Nsstring stringwithformat:@"%@/Beep.mp3",[[Nsbundle mainBundle] resourcePath]];         //Give Your Local Path

Nsurl *soundUrl= [Nsurl FileUrlWithPath:path];

_audioPlayer=[[AvAudioPlayer alloc] initwithContents ofurl:soundUrl error:nil];

_audioPlayer.volume=1.0;  //Give Volume

_audioPlayer.numberOfLoops=loop;  //Give number of loop for repeating sound

_audioPlayer.enableRate = Yes;

_audioPlayer.rate=2.0f;  //Give for fast playing sound. default value is 1.0f;

[_audioPlayer Play];
Gooseherd answered 9/7, 2016 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.