objective-c - 如何为 iOS 中的按钮添加声音?

标签 objective-c ios nssound

我想在按下按钮时播放声音。此外,还有不止一种声音。我正在使用 Xcode 4.4.1 和 Storyboard。

在.h文件中

{
    IBOutlet UIButton *playSound;
}

最佳答案

我觉得写这个类型的例子会很有趣,所以我写了它。它演示了如何在按下按钮时播放不同的随机声音:

-(IBAction)buttonPressedWithSound:(id)sender {

    int randomSoundNumber = arc4random() % 4; //random number from 0 to 3

    NSLog(@"random sound number = %i", randomSoundNumber);

    NSString *effectTitle;

    switch (randomSoundNumber) {
        case 0:
            effectTitle = @"sound1";
            break;
        case 1:
            effectTitle = @"sound2";
            break;
        case 2:
            effectTitle = @"sound3";
            break;
        case 3:
            effectTitle = @"sound4";
            break;

        default:
            break;
    }

    SystemSoundID soundID;

    NSString *soundPath = [[NSBundle mainBundle] pathForResource:effectTitle ofType:@"caf"];
    NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];

    AudioServicesCreateSystemSoundID ((CFURLRef)soundUrl, &soundID);
    AudioServicesPlaySystemSound(soundID);  
}

解释:

  • 在您的项目中添加四种声音:sound1.cafsound2.cafsound3.cafsound4 .caf.

  • 将 AudioToolbox 框架导入您的项目。并包含在 .h #import <AudioToolbox/AudioToolbox.h> 中.

  • 不要忘记通过 IBAction 将您的按钮连接到 buttonPressedWithSound .

关于objective-c - 如何为 iOS 中的按钮添加声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11888059/

相关文章:

ios - Tableview 和自定义单元格不可预测的行为

iphone - 支持多任务处理的 iOS 4 闹钟应用程序

ios - 应用程序在 iOS 13 上崩溃,因为从 -traitCollection 返回 nil,这是不允许的

ios - 将视频 URL 保存到 Core Data

ios - Canvas SwiftUI 崩溃

xcode - 声音选择器/macOS 上的系统声音列表

objective-c - 在 NSObject 中播放 NSSound(使用 Objective-C 的 Mac App)

ios - 如何使用 SegmentControl ios 将数据添加到最后选择的索引和默认索引

ios - UITableView 像轮子一样无限滚动

swift - 如何检查 NSSound 是否在 Swift 中暂停