【问题标题】:Best method to play an short audio sound on iOS 8.2在 iOS 8.2 上播放短音频的最佳方法
【发布时间】:2015-05-13 04:51:52
【问题描述】:

在 iOS 8.2 上播放音频的最佳方式是什么?

【问题讨论】:

  • AVAudioPlayer 怎么样?

标签: objective-c iphone xcode audio ios8.2


【解决方案1】:

最简单的方法是像 #import <AudioToolbox/AudioToolbox.h> 这样导入 AudioToolbox 框架,然后你需要做的就是:

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

这对于像哔哔声等非常短的声音是最好的,因为您不会像使用AVAudioPlayer 那样对声音进行太多控制。

【讨论】:

  • 谢谢。似乎对于简短的声音,这是最好的方法。
  • mp3 会打断其他声音,无法与其他人一起播放。你可能需要 caf 代替。
【解决方案2】:

使用 AVAudio - 更多地使用 AudioToolbox 进行编码,但它也更灵活(如果您将来需要它)

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];
}

【讨论】:

  • 谢谢,它对我有用。但对于简短的音频,我会尝试 C 函数。
【解决方案3】:
#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];

【讨论】:

    猜你喜欢
    • 2012-04-05
    • 2011-03-09
    • 2021-03-14
    • 2021-11-11
    • 1970-01-01
    • 2012-03-22
    • 2023-01-26
    • 2012-05-06
    • 1970-01-01
    相关资源
    最近更新 更多