简体   繁体   English

按钮无法在iOS中播放音频

[英]Button not playing audio in iOS

I uploaded a file audio.wav into my supporting files folder. 我将文件audio.wav上传到了我的支持文件文件夹中。

This is my PlayAudio.h 这是我的PlayAudio.h

#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

@interface PlayAudio : UIViewController {

}

-(IBAction) PlayIt;

@end

This is my PlayAudio.m after the implementation command 这是我执行命令后的PlayAudio.m

- (IBAction) PlayIt; {
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"audio", CFSTR ("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);

}

I then ctrl-clicked from the play button to the First Responder in my view controller and selected PlayIt. 然后,我按住ctrl键从视图按钮中单击视图控制器中的“第一响应者”,然后选择了PlayIt。 I see it's associated with Touch Up Inside. 我看到它与“ Touch Up Inside”相关联。

For some reason I can click the button, but nothing plays. 出于某种原因,我可以单击该按钮,但没有任何作用。 I'm doing this in Storyboard. 我正在情节提要中执行此操作。

You can use NSURL to get the path of your wav file and cast it to CFURLRef, check the following code: 您可以使用NSURL获取wav文件的路径并将其转换为CFURLRef,检查以下代码:

SystemSoundID soundID;
NSURL *soundPath = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"audio" ofType:@"wav"]];
if (AudioServicesCreateSystemSoundID ((CFURLRef)soundPath, &soundID) != kAudioServicesNoError) {
     AudioServicesPlayAlertSound(soundID);

}

Note, that if mute button on iphone is enable AudioServicesCreateSystemSoundID function will fail(Vibration can be used in this case:soundID = kSystemSoundID_Vibrate;). 请注意,如果启用了iPhone上的静音按钮,AudioServicesCreateSystemSoundID功能将失败(在这种情况下可以使用振动:soundID = kSystemSoundID_Vibrate;)。 If you want to play sound disregarding the mute switch, use AVAudioPlayer api. 如果要忽略静音开关播放声音,请使用AVAudioPlayer api。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM