Objective-C的新手和Xcode中的编程我无法理解为什么我的声音没有播放。我遵循了这个教程(http://www.youtube.com/watch?v=2mbCkIVF1-0)但由于某种原因我无法在iOS模拟器中播放我的声音。我使用的是故事板布局而不是nib文件,所以这可能是问题所在?我知道如何将我的按钮连接到我所拥有的故事板上,所以我很困惑,这个问题让我发疯。非常感谢任何帮助,如果我的代码错了,请指出我正确的方向,问题可能是微不足道的,无论哪种方式任何帮助都会很棒!再次感谢
SFViewController.m
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
@interface SFViewController : UIViewController <AVAudioPlayerDelegate> {
}
-(IBAction)playSound1;
-(IBAction)playSound2;
-(IBAction)playSound3;
@end
SFViewController.h
#import "SFViewController.h"
#import <AVFoundation/AVAudioPlayer.h>
@implementation SFViewController
-(IBAction)playSound1 {
NSString *path = [[NSBundle mainBundle] pathForResource:@"SeriouslyFunnySound1" ofType:@"wav"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]error:NULL];
theAudio.delegate = self;
[theAudio play];
}
-(IBAction)playSound2 {
NSString *path = [[NSBundle mainBundle] pathForResource:@"SeriouslyFunnySound2" ofType:@"wav"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]error:NULL];
theAudio.delegate = self;
[theAudio play];
}
-(IBAction)playSound3 {
NSString *path = [[NSBundle mainBundle] pathForResource:@"SeriouslyFunnySound3" ofType:@"wav"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]error:NULL];
theAudio.delegate = self;
[theAudio play];
}
答案 0 :(得分:9)
当你的“theAudio”变量超出范围时会丢失,所以玩家会停止。将变量保留为类的成员:
@implementation SFViewController
{
AVAudioPlayer* theAudio;
}
-(IBAction)playSound1 {
NSString *path = [[NSBundle mainBundle] pathForResource:@"SeriouslyFunnySound1" ofType:@"wav"];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]error:NULL];
theAudio.delegate = self;
[theAudio play];
}
答案 1 :(得分:0)
为什么要将NULL
传递给AVAudioPlayer
次?传入一个指向NSError
的nil指针并确保在启动后错误仍为零。我最好的猜测是有一些错误,而theAudio
实际上是零。
答案 2 :(得分:0)
首先确保你的IBAction方法实际被调用(在这些方法中放置一个NSLog语句,看看它们是否被调用..如果它们不是......我相信你可以自己搞清楚)< / p>
第二步:创建一个NSError对象并传入它的地址以查看问题的本质,如下所示:
NSError *err= nil
NSString *path = [[NSBundle mainBundle] pathForResource:@"SeriouslyFunnySound1"
ofType:@"wav"];
AVAudioPlayer* theAudio =
[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]
error:err];
if (!theAudio) {
NSLog(@"failed playing SeriouslyFunnySound1, error: %@", error);
}
theAudio.delegate = self;
[theAudio play];
错误的内容应该告诉你下一步该怎么做
答案 3 :(得分:0)
遇到同样的问题。以下是Swift的答案:
class ViewController: UIViewController {
var soundPlayer: AVAudioPlayer!
@IBAction func newPomodoButtonTaped(sender: UIButton) {
let soundPath = NSBundle.mainBundle().pathForResource("click_done", ofType: "wav")!
do {
soundPlayer = try AVAudioPlayer(contentsOfURL: NSURL(string: soundPath)!)
soundPlayer.prepareToPlay()
soundPlayer.numberOfLoops = 0
soundPlayer.play()
} catch let error as NSError {
print(error)
}
}
}