2012-02-25 3 views
0

Новое в IOS dev, я тестирую AVAudioplayer для воспроизведения звука на iPad2 (проект Xcode 4.2, ARC/раскадровка включена). Звук играет хорошо в симуляторе и без ошибок. Ошибка на устройстве отсутствует, но звук отсутствует.AVAudioPlayer не играет в iPad2

Был просмотр этого прекрасного храма ресурсов, но ничто из того, что я пробовал на основе отзывов, не произвело ничего, кроме оглушительной тишины iPad. Может ли кто-нибудь помочь? Мой .h:

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

@interface ViewController : UIViewController 
<AVAudioPlayerDelegate> 
{ 
    AVAudioPlayer *audioPlayer; 
    UISlider *volumeControl; 
    UILabel *timerLabel; 
    NSTimer *playbackTimer; 
} 
@property (nonatomic, retain) IBOutlet UISlider *volumeControl; 
@property (nonatomic, retain) IBOutlet UILabel *timerLabel; 
@property (nonatomic, retain) NSTimer *playbackTimer; 
@property (nonatomic, strong) AVAudioPlayer *audioPlayer; 
-(IBAction) playAudio; 
-(IBAction) stopAudio; 
-(IBAction) adjustVolume; 
@end 

Мой .m:

#import "ViewController.h" 

@implementation ViewController 
@synthesize volumeControl, timerLabel, playbackTimer, audioPlayer; 

-(void)playAudio 
{ 
    playbackTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                target:self 
                selector:@selector(updateTime) 
                userInfo:nil 
                repeats:YES]; 
    [audioPlayer play]; 
} 

-(void)stopAudio 
{ 
    [playbackTimer invalidate]; 
    [audioPlayer stop]; 
} 
-(void)adjustVolume 
{ 
    if (audioPlayer != nil) 
    { 
     audioPlayer.volume = volumeControl.value; 
    } 
} 

-(void)updateTime 
{ 
    float minutes = floor(audioPlayer.currentTime/60); 
    float seconds = audioPlayer.currentTime - (minutes * 60); 

    float duration_minutes = floor(audioPlayer.duration/60); 
    float duration_seconds = 
    audioPlayer.duration - (duration_minutes * 60); 

    NSString *timeInfoString = [[NSString alloc] 
           initWithFormat:@"%0.0f.%0.0f/%0.0f.%0.0f", 
           minutes, seconds, 
           duration_minutes, duration_seconds]; 

    timerLabel.text = timeInfoString; 
} 


-(void)audioPlayerDidFinishPlaying: 
(AVAudioPlayer *)player successfully:(BOOL)flag 
{ 
} 
-(void)audioPlayerDecodeErrorDidOccur: 
(AVAudioPlayer *)player error:(NSError *)error 
{ 
} 
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player 
{ 
} 
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player 
{ 
} 

мой viewDidLoad:

- (void)viewDidLoad { 
     [super viewDidLoad]; 

     NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
              pathForResource:@"song" 
              ofType:@"mp3"]]; 

     NSError *error; 
     audioPlayer = [[AVAudioPlayer alloc] 
         initWithContentsOfURL:url 
         error:&error]; 
     if (error) 
     { 
      NSLog(@"Error in audioPlayer: %@", 
        [error localizedDescription]); 
     } else { 
      audioPlayer.delegate = self; 
      [audioPlayer prepareToPlay]; 
     } 

    [super viewDidLoad]; 
} 

ответ

0

Убедитесь, что файл действительно формат mp3. Убедитесь, что вы копируете файл в пакет и не отключаетесь от локального пути на рабочем столе. Проверьте громкость устройства. Проверьте возврат BOOL от вызова воспроизведения. все это возможные объяснения.

+0

Да, файл определенно mp3, файл в комплекте, максимальный объем устройства, но, несмотря на то, что кнопка запуска правильно связана с IB can not, лог возвращается на любой из них, или не работает? – prk

+0

попробуйте перезагрузить симулятор/устройство. иногда, когда звук изменился, например, при использовании приложения, такого как Boom, это может случиться. – user1046037

+0

, так что из этого было? – Toad

0

Разве это не звучит вообще? Нет звуков даже при подключенных наушниках? Если звук через встроенный динамик просто звучит, но звучит через наушники, убедитесь, что громкость звонка/звука вашего устройства не отключена. Проверьте тумблер сбоку (если у вас установлен этот параметр для отключения звука или блокировки ориентации). Колокол не должен быть вычеркнут. Просто потому, что вы нажимаете кнопку увеличения громкости, это не значит, что она не отключена от динамика. Вы тестировали видеоролики или музыкальные файлы YouTube, чтобы у iPad не было проблем с оборудованием?

Смежные вопросы