在iOS中播放短音

Bes*_*esi 58 audio ios

我想我可以使用AVAudioPlayer播放声音,但是,我需要的是只打一短声,我也不需要通过音量等任何循环或细粒度的控制

是否有捷径可寻?

bbu*_*bum 88

其他答案中的每一个都泄漏了内存(除非为其中一个答案启用了ARC )......奇怪的是,最初标记为正确的答案retainCount没有明显的原因.

如果你有alloc/init什么东西,它需要被释放(除非你使用ARC).

如果你打电话,AudioServicesCreateSystemSoundID()你必须处理产生的声音.

请参阅音频UI声音示例.

基本上:

@interface MyClass:UI*ViewController // fixed
{
     SystemSoundID mySound;
}
@implementation MyClass
- (void) viewDidLoad {
    [super viewDidLoad];
    AudioServicesCreateSystemSoundID(.... URL ...., &mySound);
}

- (void) playMySoundLikeRightNowReally {
    AudioServicesPlaySystemSound(mySound);
}

- (void) dealloc {
   AudioServicesDisposeSystemSoundID(mySound);
   [super dealloc]; // only in manual retain/release, delete for ARC
}
@end
Run Code Online (Sandbox Code Playgroud)

为完整
起见:添加AudioToolbox.framework
#import <AudioToolbox/AudioToolbox.h>

  • 使用ARC时,请务必使用__bridge:`AudioServicesCreateSystemSoundID((__ bridge CFURLRef)mySoundNSURL,&_ mySound);` (10认同)
  • 由于stickling在这里很流行:你的例子在`NSObject`的子类上调用`[super viewDidLoad]`.;) (2认同)

Him*_*ngh 43

对于短的声音片段(少于30秒),有一个非常好的SystemSounds库.

优点:您无需单独管理音量设置.声音在一个单独的线程中播放,加载和播放音频片段的速度很快.简而言之,您将此剪辑视为另一个系统声音.

缺点:您无法提供单独的音频控制设置.它与系统声音的设置有关.你玩的时间不能超过30秒.您可能无法应用任何声音过滤器来增强音频效果.

肯定有更多的优点和缺点,但这些是我能想到的,在我的头脑中.

使用此导入:<AudioToolbox/AudioToolbox.h> 添加AudioToolbox Framework然后调用以下方法,如[self playSound],无论你想在哪里播放剪辑.

-(void) playSound {
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"changeTrack" ofType:@"aif"];
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);
    AudioServicesPlaySystemSound (soundID);
    [soundPath release];
}
Run Code Online (Sandbox Code Playgroud)

  • 该代码泄漏声音并调用`retainCount`(以及注释的`[soundPath release]`)表示对内存管理有点误解.... (9认同)

Sur*_*gch 23

迅速

这里的其他答案使用Objective-C,所以我在这里提供一个Swift版本.Swift使用自动引用计数(ARC),所以我不知道这个答案有任何内存泄漏问题(正如在接受的答案中所警告的那样).

使用AudioToolbox

AudioToolbox当您不需要太多控制它们的播放时,您可以使用该框架播放短音.

以下是如何设置它:

import UIKit
import AudioToolbox

class PlaySoundViewController: UIViewController {

    var soundURL: NSURL?
    var soundID: SystemSoundID = 0

    @IBAction func playSoundButtonTapped(sender: AnyObject) {

        let filePath = NSBundle.mainBundle().pathForResource("yourAudioFileName", ofType: "mp3")
        soundURL = NSURL(fileURLWithPath: filePath!)
        if let url = soundURL {
            AudioServicesCreateSystemSoundID(url, &soundID)
            AudioServicesPlaySystemSound(soundID)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

使用AVAudioPlayer

通过导入AVFoundation框架,您可以使用AVAudioPlayer.它适用于短音频剪辑和长歌.与使用AudioToolbox方法相比,您还可以更好地控制播放.

以下是如何设置它:

import UIKit
import AVFoundation

class PlaySoundViewController: UIViewController {

    var mySound: AVAudioPlayer?

    // a button that plays a sound
    @IBAction func playSoundButtonTapped(sender: AnyObject) {
        mySound?.play() // ignored if nil
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // initialize the sound
        if let sound = self.setupAudioPlayerWithFile("yourAudioFileName", type: "mp3") {
            self.mySound = sound
        }
    }

    func setupAudioPlayerWithFile(file: NSString, type: NSString) -> AVAudioPlayer? {

        let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
        let url = NSURL.fileURLWithPath(path!)
        var audioPlayer: AVAudioPlayer?
        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: url)
        } catch {
            print("Player not available")
        }

        return audioPlayer
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:


Ars*_*wez 17

最近,我用这段代码播放短mp3音频,效果很好: -

在@implementation下面声明这个

NSString *path;

NSURL *url;

//where you are about to add sound 

path =[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"quotes_%d",soundTags] ofType:@"mp3"];

    url = [NSURL fileURLWithPath:path];
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    [player setVolume:1.0];
    [player play];

//just add AVFoundation framework
Run Code Online (Sandbox Code Playgroud)

  • `[player setVolume:1.0];`应该在创建播放器后出现. (3认同)

Sch*_*mas 9

我用这段代码在iOS上播放一个简短的aiff-sound

#import <AudioToolbox/AudioServices.h> 

SystemSoundID completeSound;
NSURL *audioPath = [[NSBundle mainBundle] URLForResource:@"downloadCompleted" withExtension:@"aiff"];
AudioServicesCreateSystemSoundID((CFURLRef)audioPath, &completeSound);
AudioServicesPlaySystemSound (completeSound);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


Rob*_*ack 7

SIMPLE CLEAN SWIFT 3版

我喜欢更多地控制我的声音所以我正在使用AVFoundation.

import AVFoundation

class TodayViewController: UIViewController {

  var clink: AVAudioPlayer?
  var shatter: AVAudioPlayer?

  override func viewDidLoad() {
    super.viewDidLoad()

    // initialize the sound
    shatter = setupAudioPlayer(withFile: "shatter", type: "wav")
    clink = setupAudioPlayer(withFile: "clink", type: "wav")
  }

  func setupAudioPlayer(withFile file: String, type: String) -> AVAudioPlayer? {
    let path = Bundle.main.path(forResource: file, ofType: type)
    let url = NSURL.fileURL(withPath: path!)
    return try? AVAudioPlayer(contentsOf: url)
  }

  func onClick() {
    clink?.play()
  }
}
Run Code Online (Sandbox Code Playgroud)

确保声音文件已添加到项目中并导入AVFoundation.


Con*_*nor 6

我的答案是比尔的答案,但我在没有类 init 或 dealloc 的情况下使用它,仅在需要时加载声音并在播放后直接释放声音:

- (void)playSound:(NSURL *)url
    SystemSoundID ssID = 0;
    AudioServicesCreateSystemSoundID((CFURLRef)url, &ssID);
    AudioServicesAddSystemSoundCompletion(ssID, NULL, NULL, (AudioServicesSystemSoundCompletionProc)MyAudioServicesSystemSoundCompletionProc, NULL);
    AudioServicesPlaySystemSound(ssID);
}

void MyAudioServicesSystemSoundCompletionProc (SystemSoundID  ssID, void *clientData) {
    AudioServicesDisposeSystemSoundID(ssID);
}
Run Code Online (Sandbox Code Playgroud)