2014-03-24 156 views
0

我已经构建了一些代码,当按钮被点击时应该播放音频。代码中没有错误,但是当我打开iOS模拟器并按下按钮时,没有声音播放。该按钮执行轻击动画,但没有任何反应。 我有AVFoundation和AudioToolbox框架。 我也有我的音频文件的资源。 我没有使用断点。 该按钮设置为在Touch Up Inside时使用'playAudio:'第一响应者。声音没有在iOS模拟器中播放。没有错误

这里是我的 'ViewController.h' 文件:

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

@interface ViewController : UIViewController 

@property (strong, nonatomic) AVAudioPlayer *audioPlayer; 
- (IBAction)playAudio:(id)sender; 

@end 

这里是我的 'ViewController.m' 文件:

#import "ViewController.h" 
#import <AVFoundation/AVFoundation.h> 
#import <AudioToolbox/AudioToolbox.h> 

@interface ViewController() 

@end 

@implementation ViewController 

- (IBAction)playAudio:(id)sender { 
    AVAudioPlayer *audioPlayer; 
    NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"AudioFile" ofType:@"wav"]; 
    NSURL *audioURL = [NSURL fileURLWithPath:audioPath]; 
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil]; 
    [audioPlayer play]; 
    sleep(5); 
}; 

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
@end 

的音频段大约为3秒。

任何帮助非常感谢! 谢谢!

+0

您的计算机是否静音并且音量设置得足够高以至于听不到? – Kevin

+0

你试过这个http://stackoverflow.com/questions/12260120/no-sound-in-simulator-of-xcode-4-4-1-in-iphone? –

回答

1

我对ios相当陌生,但我有同样的问题,并能够解决它。

我只是说过我是AVAudioPlayer变量作为全局变量,并呼吁

[audioPlayer prepareToPlay]; 

[audioPlayer play]; 

只是打电话prepareToPlay didnt解决它,我必须声明全局变量来为它工作。 不知道为什么这会对模拟器产生影响,但它现在起作用。

0

播放声音/音乐文件在objective-c, 我有同样的问题,并能够解决它与下面的代码。

.h file 

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

@interface ViewController : UIViewController 

- (IBAction)actionOnPlayButton:(id)sender; 
- (IBAction)actionOnStopButton:(id)sender; 

- (void)playSound ; 

@end 

.m file 



#import "ViewController.h" 

    @interface ViewController() 

    @end 

    @implementation ViewController 

    AVAudioPlayer *audioPlayer; 

    - (void)viewDidLoad { 
     [super viewDidLoad]; 
     self.title = @"Play Music"; 
    } 

    -(void)playSound{ 

     NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"sound10" 
                    ofType:@"mp3"]; 
     NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; 
     audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; 
     audioPlayer.numberOfLoops = -1; 

     [audioPlayer prepareToPlay]; 

     [audioPlayer play]; 
    } 



    - (IBAction)actionOnPlayButton:(id)sender { 

     [self playSound]; 
    } 

****上面的代码行中,它会正常工作... 注: - 不要忘了导入以下架构: - **

#进口 #进口

相关问题