1. 程式人生 > >字符串變枚舉變量

字符串變枚舉變量

AS reat enum close pat nsbundle In bject lam


1、以一個點擊按鈕播放音效為例

引入音頻管理文件
    #import <AVFoundation/AVFoundation.h>

2、創建枚舉值

    typedef NS_ENUM(NSInteger, VoiceType) {
        VoiceTypeIsWav = 0, // wav
        VoiceTypeIsMp3 = 1, // mp3
        VoiceTypeIsAPE = 2, // ape
        VoiceTypeIsOther = 3 // 其他
    };
    NSString *const VoiceTypeStringMap[] = {
        [VoiceTypeIsWav] = @"wav",
        [VoiceTypeIsMp3] = @"mp3",
        [VoiceTypeIsAPE] = @"ape",
        [VoiceTypeIsOther] = @"Other"
    };

3、播放音頻文件方法抽取

    /************ 播放音效 *****************************/
    - (void)playSoundEffect:(NSString *)name withType:(VoiceType)type {
        // 播放掃描二維碼的聲音
        SystemSoundID soundID;
        NSString *strSoundFile = [[NSBundle mainBundle] pathForResource:name ofType:VoiceTypeStringMap[type]];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile],&soundID);
        AudioServicesPlaySystemSound(soundID);
    }

4、按鈕點擊播放音效

    /************ 點擊開關燈按鈕就會調用 *****************************/
    - (void)OpenOrClosedLamp:(UIButton *)button {
        // 播放音效
        [self playSoundEffect:@"btn_press_voice_2" withType:VoiceTypeIsWav];
    }

字符串變枚舉變量