简体   繁体   English

在viewDidLoad上播放声音-Xcode

[英]Playing sound on viewDidLoad - Xcode

I'm facing a small issue with playing sounds upon loading of the view (and ultimately upon other actions that are performed if this code works) 我在加载视图时(以及最终在此代码有效的情况下执行的其他操作)播放声音时遇到一个小问题

The Problem: The sound does not play on the phone when the view is loaded. 问题:加载视图时,声音无法在电话上播放。 HOWEVER, I can hear the sound from my iphone if I step through the code after adding a breakpoint on: 但是,如果在以下位置添加断点后逐步执行代码,则可以从iPhone听到声音:

[click play]

I have obtained the following code from an online tutorial and copied it to my viewDidLoad method: 我从在线教程中获得了以下代码,并将其复制到了我的viewDidLoad方法中:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]                                                                                                                  pathForResource:@"States" ofType:@"mp3"]];
    AVAudioPlayer *click  = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile  error:nil];
    [click play]; // Breakpoint is here

}

Things I've done: 我所做的事情:

  • Imported AudioToolbox/AudioToolbox.h and AVFoundation/AVFoundation.h in my header file 在我的头文件中导入了AudioToolbox / AudioToolbox.hAVFoundation / AVFoundation.h
  • Executed the code with and without breakpoints --> With the breakpoints and the stepping through I can hear the sound; 在有断点和无断点的情况下执行代码->通过断点和单步执行,我可以听到声音; without I cant. 没有我不能。

I would greatly appreciate it if I can get some suggestions or inputs to try it. 如果能得到一些建议或投入尝试,我将不胜感激。 Or even another way to implement audio in my application 甚至是在我的应用程序中实现音频的另一种方法

Thank you. 谢谢。

Your audio player object, "click", will be deallocated as soon as viewDidLoad finishes, since it's assigned to a local variable. viewDidLoad完成后,音频播放器对象“ click”将被重新分配,因为它已分配给局部变量。 You need to create an ivar or property for your player. 您需要为播放器创建一个ivar或属性。

musicFile doesn't contain a URL for a music file (or, indeed, any file). musicFile不包含音乐文件(或实际上任何文件)的URL。 It contains the URL of Application itself. 它包含应用程序本身的URL。 What you want to do is something more along the lines of: 您想要做的事情更多是:

musicFile = [[NSBundle mainBundle] URLForResource:@"musicFile" withExtension:@"caf"];

Also, for playing small short audio clips, you probably just want to use AudioServices 另外,对于播放小型音频短片,您可能只想使用AudioServices

One-time initialization (in viewDidLoad, or statically): 一次性初始化(在viewDidLoad中或静态进行):

static SystemSoundID    sound;
static dispatch_once_t  onceToken;

dispatch_once(&onceToken, ^{
    NSURL*      url = [[NSBundle mainBundle] URLForResource:@"statusChanged" withExtension:@"caf"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &sound);
});

Then to play the sound: 然后播放声音:

AudioServicesPlaySystemSound(sound);

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

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