2014-03-24 155 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]; 
    } 

****上面的代碼行中,它會正常工作... 注: - 不要忘了導入以下架構: - **

#進口 #進口

相關問題