1

I found that using AVAudioFoundation should be the easiest way to play an mp3 on objective-c, but I don't know what I'm doing wrong here. No sound on either the device or the simulator. I imported the framework and all the other "normal" things, but it just keep not playing. What is wrong in this code?

NSString *path = [[NSBundle mainBundle] pathForResource:@"DuomoDiFirenze" ofType:@"mp3"];
AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio prepareToPlay];
[theAudio play];
Alberto Schiariti
  • 1,546
  • 2
  • 15
  • 31
  • not sure which player I am using at home, but some functions doesn't work on simulator for sure, eg volume up. I highly recommend to skip simulators while doing Audio / Video stuff –  Oct 12 '12 at 16:25
  • As I wrote, I tried it also on the device, but it's the same. No sound at all. I think the problem is not the simulator. – Alberto Schiariti Oct 12 '12 at 16:27
  • if I would know what is the error, than I would set an error and give it to `initWithContentsOfURL:[NSURL fileURLWithPath:path] error:` and I would log it after that –  Oct 12 '12 at 16:29
  • Maybe same problem as http://stackoverflow.com/questions/7692866/avaudioplayer-stops-playing-immediately-with-arc/7744831#7744831 – Mattias Wadman Oct 12 '12 at 16:40

2 Answers2

2

Do you compile with ARC? if so make sure to keep a reference to the AVAudioPlayer instance as else ARC will make sure to release it for you and the audio playback will stop immediately.

Mattias Wadman
  • 11,172
  • 2
  • 42
  • 57
  • 1
    Yeah, I do use ARC. But what do you mean with "keep a reference to the AVAudioPlayer instance"? NVM. I'm reading your comment on the other answer. – Alberto Schiariti Oct 12 '12 at 16:46
  • 1
    To assign it to a property or a instance variable for example. – Mattias Wadman Oct 12 '12 at 16:47
  • This solved it for me. The "free" variable (I don't know how it is called actually, when a var is not attached to any object, but in a loop or something, declared on the fly) didn't work, but as a property, AVAudioPlayer worked as supposed. – Vladimir Despotovic Apr 11 '18 at 23:09
0

So when you declare AVAudioPlayer * theAudio as a property of whichever object you are using it it, it will work. That's the only thing you are missing.

Vladimir Despotovic
  • 3,200
  • 2
  • 30
  • 58